Nicholas Adkins Nicholas Adkins - 17 days ago 6
MySQL Question

PHP displaying rows

Still new to PHP. I'd like to display few rows from database using ID's stored in the array. Actually it displays only the first row (with ID=2) and i'm looking for the way to display all of them (4 rows).

$i=0;
if($sql1= mysqli_query($conn, "SELECT * FROM table"))
{
$arr = array(2,3,5,7);
$sql2= mysqli_query($conn, "SELECT * FROM table WHERE id='".$arr[$i]."'");
while($row1 = mysqli_fetch_assoc($sql2))
{
echo $row1['id'];
echo $row1['content']; //display some rows
$i=$i+1;
}
}


Anyone know how to achieve that?

Answer

The problem in your code is you use an array, but never loop through the elements. Also, instead of executing the query multiple times, you could get the results with a single query:

$i=0;
if($sql1= mysqli_query($conn, "SELECT * FROM table"))
{
    $arr = array(2,3,5,7);
    $ids = implode(',',$arr);
    $sql2= mysqli_query($conn, "SELECT * FROM table WHERE id in (".$ids.")");
    while($row1 = mysqli_fetch_assoc($sql2)) {
        echo $row1['id'];
        echo $row1['content'];  //display some rows
        $i=$i+1; 
    }
}

If you actually need to loop through the array, you could do that like this:

if($sql1= mysqli_query($conn, "SELECT * FROM table"))
{
    $arr = array(2,3,5,7);
    for($i = 0; $i < sizeOf($arr);$i++) {
        $sql2= mysqli_query($conn, "SELECT * FROM table WHERE id='".$arr[$i]."'");
        while($row1 = mysqli_fetch_assoc($sql2)) {
            echo $row1['id'];
            echo $row1['content'];  //display some rows
        }
    }
}