0

I'm in the process of building an iOS app that uses a webservice for data. The webservice consists of PHP, MySQL database.

I've successfully managed to JSON encode the data returned, but the code I am using only seems to encode 1 row.

I wanted to get some advice on how to encode multiple rows?

Thanks.

<?php
$username = "root";
$password = "*******";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");

//print "Connected to MySQL<br>";

$selected = mysql_select_db("newtest",$dbh)
or die("Could not select first_test");

$query = "SELECT * FROM MyGuests ";
$result=mysql_query($query);

echo json_encode(mysql_fetch_assoc($result));

?>
  • You are only fetching one row of the result set. You need to fetch them all. – Mike Brant Nov 25 '14 at 15:48
  • Please, [don't use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php), They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://us1.php.net/pdo) or [MySQLi](http://us1.php.net/mysqli). – Jay Blanchard Nov 25 '14 at 15:55
  • Thanks for this, back to the drawing board for me! – freshfanatic Nov 25 '14 at 16:01
  • Possible duplicate of [How to encode json with multiple rows?](https://stackoverflow.com/questions/51657380/how-to-encode-json-with-multiple-rows) – Beulah Akindele Aug 10 '18 at 18:12

1 Answers1

2
$query = "SELECT * FROM MyGuests ";
$result=mysql_query($query);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
  $rows[] = $r;
}
print_r json_encode($rows);
Dima
  • 8,586
  • 4
  • 28
  • 57
  • You're mixing `mysql_` and `mysqli_` functions. That will not work. – Jay Blanchard Nov 25 '14 at 15:55
  • Hi, thanks for this. I've implemented this change, and previously when accessing the URL for this query on a browser it displayed the single row as JSON, but not the page shows blank. Have I done something wrong or is this expected? Sorry for the noob questions! – freshfanatic Nov 25 '14 at 15:58