You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中SQL OR语句异常:查询结果仅返回第一条数据问题求助

Troubleshooting: Only First Record Saves to $oq Variable

Hey there! Let's dig into why your $oq variable is only holding the first record (ID 3) even though your SQL query returns both IDs 3 and 4 in phpMyAdmin. This is a super common pitfall, and it almost always boils down to how you're fetching results from your database in PHP.

Common Causes & Fixes

1. You're Fetching Only a Single Row, Not All Results

Depending on whether you're using PDO or MySQLi, the method to get all rows differs. Here's how to fix both scenarios:

If Using PDO:

If you used fetch() instead of fetchAll(), you'll only get the first row. Switch to fetchAll() to grab every record returned by your query:

// ❌ Wrong: Only fetches the first row
$oq = $stmt->fetch(PDO::FETCH_ASSOC);

// ✅ Correct: Fetches all rows into an array
$oq = $stmt->fetchAll(PDO::FETCH_ASSOC);

If Using MySQLi:

mysqli_fetch_assoc() retrieves one row at a time. To collect all rows, you need to loop through the result set and push each row into your $oq array:

// ❌ Wrong: Only gets the first row
$oq = mysqli_fetch_assoc($result);

// ✅ Correct: Loops through all rows and stores them
$oq = [];
while ($row = mysqli_fetch_assoc($result)) {
    $oq[] = $row;
}

2. You're Not Looping Through the $oq Array to Output All Data

Even if you have all rows in $oq, if you're only accessing the first element directly (like $oq['id']), you'll only see the first record. Use a loop to iterate through every item in the array:

// Loop through each record in $oq
foreach ($oq as $record) {
    // Output your target code here, e.g.:
    echo "ID: " . $record['id'] . "<br>";
}

Quick Verification Step

Double-check that your SQL query really returns 2 rows by running it directly in phpMyAdmin. If it does, the fixes above should resolve the issue.


内容的提问来源于stack exchange,提问作者Florian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:11:52