3

I've got a database with 5 columns and multiple rows. I want to fetch the first 3 rows and echo them as an array. So far I can only get the first row (I'm new to PHP and mysql). Here's my PHP so far:

//==== FETCH DATA
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_row($result);    

//==== ECHO AS JSON
echo json_encode($array);

Help would be much appreciated.

CaribouCode
  • 13,156
  • 22
  • 91
  • 166

5 Answers5

13

You need to loop through the results. mysql_fetch_row gets them one at a time.

http://php.net/manual/en/function.mysql-fetch-row.php

The code would end up like:

$jsonData = array();
while ($array = mysql_fetch_row($result)) {
    $jsonData[] = $array;
}
echo json_encode($jsonData);
//json_encode()

PLEASE NOTE The mysql extension is deprecated in PHP 5.5, as stated in the comments you should use mysqli or PDO. You would just substitute mysqli_fetch_row in the code above. http://www.php.net/manual/en/mysqli-result.fetch-row.php

Gandalf
  • 12,622
  • 27
  • 90
  • 148
Schleis
  • 37,924
  • 7
  • 65
  • 84
2

According to the PHP Documentation mysql_fetch_row (besides that it's deprecated and you should use mysqli or PDO)

Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.

so you need for example a while loop to fetch all rows:

$rows = array();

while ($row = mysql_fetch_row($result)) {
    $rows[] = $row;
}

echo json_encode($rows);

I leave it to you how to only fetch 3 rows :)

stefreak
  • 1,382
  • 10
  • 29
2

I do like this while quering an ODBC database connection with PHP 5.5.7, the results will be in JSON format:

$conn = odbc_connect($odbc_name, 'user', 'pass');
$result = odbc_exec($conn, $sql_query);

Fetching results allowing edit on fields:

while( $row = odbc_fetch_array($result) ) { 
     $json['field_1'] = $row['field_1'];
     $json['field_2'] = $row['field_2'];
     $json['field_3'] = $row['field_1'] + $row['field_2'];

     array_push($response, $json); 
  }

Or if i do not want to change anything i could simplify like this:

while ($array = odbc_fetch_array($result)) { $response[] = $array; }

What if i want to return the results in JSON format?, easy:

echo json_encode($response, true);

You can change odbc_fetch_array for mysqli_fetch_array to query a MySql db.

Jhollman
  • 1,950
  • 21
  • 19
0

You need to put this in some kind of a loop, mysql_fetch_row returns results one at a time.

See example: http://www.php.net/manual/en/mysqli-result.fetch-row.php#example-1794

dcbarans
  • 482
  • 9
  • 14
-1

$result = mysql_query( "SELECT * FROM $tableName ORDER BY id LIMIT 3");

$json = array(); while($array = mysql_fetch_row($result)){

$json[] = $array; }

echo json_encode($json);

Manomite
  • 59
  • 4