Reputation: 309
I am trying to convert my MYSQL table data into JSON. I am trying with json_encode(). But it does not work. It does not return anything. I have checked the console,doesn't even throw any errors. What am i missing?
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","maps") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from locations";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray[] = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
?>
Upvotes: 6
Views: 20812
Reputation: 865
Add this line and it will work fine:
mysqli_set_charset($conn, 'utf8');
Upvotes: 6
Reputation: 21
I had the same funny issue (using PDO) and in my case it helped to add the UTF-8 setting query - either of the two:
$conn->query("SET CHARACTER SET utf8;");
$conn->query("SET collation_connection = utf8_unicode_ci;");
Upvotes: 2
Reputation: 1
I had a similar problem but when I tried the solutions above it returned me a 1-dimensional array of JSON-like strings instead of a 2-d array. I solved it by running $.parseJSON
(jQuery) on each element.
Upvotes: 0
Reputation: 228
I know this is old, but I didn't found the explanation of this error, in my case, the problem was to keept the values on the DB with accent mark (Ej: cafetería). the var_dump($emparray ) certanly show information, but the echo json_ecode($emparray ) shows nothing. The solution?
This is my DB conection:
$connection = mysqli_connect('ip,'user','pass','dbname')
or die("Error " . mysqli_error($connection));
Only need to add the correct charset:
mysqli_set_charset( $connection, 'utf8');
Expetcs this work for others.
Upvotes: 17
Reputation: 6773
try this
while ( $row = $result->fetch_assoc() ){
$emparray[] = json_encode($row);
}
echo json_encode( $emparray );
or
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = json_encode($row);
}
echo json_encode($emparray);
or
$emparray = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $emparray );
instead of
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
Upvotes: 10