Reputation: 63
I have this php code to build the result of my MYSQL into JSON:
<?php
$mysql_db_hostname = "localhost";
$mysql_db_user = "root";
$mysql_db_password = "";
$mysql_db_database = "essensplan";
$con = @mysqli_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password, $mysql_db_database);
if (!$con) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
$var = array();
$sql = "SELECT * FROM beispiel";
$result = mysqli_query($con, $sql);
while($obj = mysqli_fetch_object($result)) { $var[] = $obj; }
echo '{"users":'.json_encode($var).'}';
?>
The PHP script work on my Apache and the PHP Version is 5.5.11.
But when I call the script, there only shows {users:}
and the json data from the mysql data base is missed. Have anybody an idea?
EDIT: I found a solution. After connect to the database set this:
mysqli_set_charset($con, 'utf8');
Upvotes: 0
Views: 296
Reputation: 560
You should modify the part after you've checked for the connection error as so:
$var = array();
$sql = "SELECT * FROM beispiel";
$result = mysqli_query($con, $sql);
while($obj = mysqli_fetch_object($result)) {
$var['users'][] = $obj;
}
echo json_encode($var);
If for example your returned results are arrays as so
array(
'name' => 'person1',
'age' => 25
),
array(
'name' => 'person2',
'age' => 30
),
array(
'name' => 'person3',
'age' => 22
)
Then your returned JSON response will be as so:
{"user":[{"name":"person1","age":25},{"name":"person2","age":30},{"name":"person3","age":22}]}
Hope that solved your problem, if any modifications are required, please provide more info.
Upvotes: 1