Udit Bhardwaj
Udit Bhardwaj

Reputation: 1781

how to fetch multiple rows with same field value from a mysql database using php

|touser| fromuser |  msg  |
|  A   |    B     | hi    |
|  A   |    B     | hello |
|  C   |    D     | bye   |
|  C   |    E     | hey   |

when i use following query in mysql workbench it shows the desired result that is all the rows with given name:

select * from db.table1 where touser in ('A');

output:

|touser| fromuser |  msg  |
|  A   |    B     | hi    |
|  A   |    B     | hello |

but when i pass query from php commands the resultant array contains only first record

<?php
 //connection establishing commands
 $sql="select * from db.table1 where touser in ('A')";

 $result=mysqli_query($link, $sql);

 $data=mysqli_fetch_array($result,MYSQLI_NUM);

 print_r($data);

 //other stuff;
 ?>

output:

    Array ( [0] => A [1] => B [2] => Hi )

am I missing something in the php commands?

Upvotes: 0

Views: 7601

Answers (1)

nathangiesbrecht
nathangiesbrecht

Reputation: 940

You're PHP is simply returning the first row of the MySQL result set.

You'll want to replace $data=mysqli_fetch_array($result,MYSQLI_NUM);

with

while ($data = mysqli_fetch_array($result, MYSQLI_NUM)) {
    print_r($data);
}

Which will iterate over each row of the result set. In other words, the mysqli_fetch_array function doesn't fetch the entire result set as an array, it simply returns a single row, and then moves the row "pointer" to the next row.

Upvotes: 2

Related Questions