PHP中SQL OR语句异常:查询结果仅返回第一条数据问题求助
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

