0
  • 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?

1
  • put your while loop inside for loop. As while loop will run only for last result. Commented Jan 13, 2015 at 5:10

5 Answers 5

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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 />';
  } 

Comments

0
$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/>';
}

Comments

0
 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 />';
  } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.