Reputation: 1101
Database (book table)
serialID price
0001 10.00
0001
30.00
0002 15.00
0003(A) 9.00
0004(B) 5.00
0005 3.00
Code
$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
?
Upvotes: 0
Views: 127
Reputation: 16
for($i = 0; $i < count($serialID); $i++)
{
$r = mysqli_query($sql);
$sql=select serial from book where serial like "$serialID[$i]"
}
while($row = mysqli_fetch_array($r)
{
echo $row['serial'].'<br />';
}
Upvotes: 0
Reputation: 44581
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.
Upvotes: 1
Reputation: 91
$serialID = array("0001","0002","0003","0004","0005");
//DB Connection
foreach($serialID as $serial){
$q = "select serial from book where serial like '%".$serial."%' limit 1";
$r = mysqli_query($dbc, $q);
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)
echo $row['serial'].'<br/>';
}
Upvotes: 0
Reputation: 520
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 />';
}
Upvotes: 0
Reputation: 3419
Edit: you always override your select statement in the for loop before quering it. So only the last query with the last serial is executed
Upvotes: 0