25

I am wondering if there a function in php that can allow me put all my selected data in an array .Currently i am using mysql_fetch_array and as i have read in the manual,that function won't fetch every record in the table.

$result = mysql_query("SELECT * FROM $tableName");            
$array = mysql_fetch_array($result);

  echo json_encode($array);
4
  • 2
    Those mysql_... functions are old and unsafe. You should used mysqli or better PDOs - php.net/manual/en/book.mysqli.php, php.net/manual/en/book.pdo.php Commented Jun 29, 2012 at 15:16
  • As Raeki said, mysql are quite old, but other than that, if you still want to loop trough the result, you can do it with following code: $allRows = array(); while($row = mysql_fetch_array($result) {$allRows[] = $row } Commented Jun 29, 2012 at 15:18
  • 2
    Please don't use mysql_* functions in new code. They were removed from PHP 7.0.0 in 2015. Instead, use prepared statements via PDO or MySQLi. See Why shouldn't I use mysql_* functions in PHP? for more information. Commented Jun 29, 2012 at 15:28
  • In case you're copy/pasting, toske needs to add a closing ) for his while. $allRows = array(); while($row = mysql_fetch_array($result)) {$allRows[] = $row } Commented Feb 6, 2013 at 19:53

6 Answers 6

75

I would suggest the use of MySQLi or MySQL PDO for performance and security purposes, but to answer the question:

while($row = mysql_fetch_assoc($result)){
     $json[] = $row;
}

echo json_encode($json);

If you switched to MySQLi you could do:

$query = "SELECT * FROM table";
$result = mysqli_query($db, $query);

$json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo json_encode($json );
Sign up to request clarification or add additional context in comments.

Comments

11
  1. Loop through the results and place each one in an array

  2. use mysqli_fetch_all() to get them all at one time

Comments

9

You could try:

$rows = array();
while($row = mysql_fetch_array($result)){
  array_push($rows, $row);
}
echo json_encode($rows);

Comments

1
$name=array(); 
while($result=mysql_fetch_array($res)) {
    $name[]=array('Id'=>$result['id']); 
    // here you want to fetch all 
    // records from table like this. 
    // then you should get the array 
    // from all rows into one array 
}

Comments

1

This method is also very nice, you can try it.

 try {
       while ($row=mysqli_fetch_array($res)) {
        array_push($row...);           
    }    
} catch (Exception $e) {
     print($e->getMessage());
}

1 Comment

This unexplained answer contains invalid syntax.
0

you can call mysql_fetch_array() for no_of_row time

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.