Database (book table)
serialID price
0001 10.00
0001 30.00
0002 15.00
0003(A) 9.00
0004(B) 5.00
0005 3.00Code
$serialID = array("0001","0002","0003","0004","0005"); //DB Connection for($i = 0; $i < count($serialID); $i++) { $q = "select serial from book where serial like \"$serialID[$i]\" limit 1"; $r = mysqli_query($dbc, $q); } while($row = mysqli_fetch_array($r, MYSQLI_ASSOC) { echo $row['serial'].'<br />'; }From my code, I can only get the last serialID only. How do I retrieve every serialID in
$row?
-
put your while loop inside for loop. As while loop will run only for last result.Manoj Sharma– Manoj Sharma2015-01-13 05:10:09 +00:00Commented Jan 13, 2015 at 5:10
Add a comment
|
5 Answers
You can use this instead :
$q = "select serial from book where serial like '%"
. implode($serialID, "%' OR serial LIKE '%") . "%'";
$r = mysqli_query($dbc, $q);
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)
echo $row['serial'].'<br />';
In your for loop you SELECT all of the rows, but only the last instance is saved in a variable ( in the last iteration of the for loop), so you fetch only it in the while loop.
P.S. You could also work it out by putting your while loop in the end of the for loop, but the code above is just not that cumbersome.
Comments
i hope you have did a mistake that in the query you have kept limit 1 so that's the reason you are getting only last record
for($i = 0; $i < count($serialID); $i++)
{
$sql=select serial from book where serial like \"$serialID[$i]\"
$r = mysqli_query($sql);
}
while($row = mysqli_fetch_array($r)
{
echo $row['serial'].'<br />';
}