Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all mysql selected rows into an array

Tags:

arrays

php

mysql

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);
like image 461
Gandalf Avatar asked Jun 29 '12 15:06

Gandalf


People also ask

What is Mysql_result () function?

The mysql_result() function returns the value of a field in a recordset. This function returns the field value on success, or FALSE on failure.

How do I create an array query in MySQL?

By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Your example shows it best, you get the same value 18 and you can access it via $v[0] or $v['type'] . Show activity on this post. Show activity on this post.


3 Answers

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 );
like image 142
Mike Mackintosh Avatar answered Oct 19 '22 14:10

Mike Mackintosh


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

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

like image 10
John Conde Avatar answered Oct 19 '22 14:10

John Conde


You could try:

$rows = array();
while($row = mysql_fetch_array($result)){
  array_push($rows, $row);
}
echo json_encode($rows);
like image 8
Brandon Ferrara Avatar answered Oct 19 '22 12:10

Brandon Ferrara