Reputation: 1827
I know this has been asked thousands of times, but I still can't wrap my head around it. Here it comes: I want to encode my database data into json.
I had my code working under an old version of php using msql_connect, etc in stead of mysqli. I updated the server yesterday and I can't get it working with mysqli.
This is my code, returning nothing, not null, no empty brackets, nothing.
<?php
$mysqli = new mysqli("$host", "$username", "$password","$db_name");
$myQuery = "SELECT * FROM myTable ORDER BY date DESC LIMIT 4";
$result = $mysqli->query($myQuery);
$data = array();
while($row = mysqli_fetch_assoc($result)) {
$data['nameOfArray'][] = $row;
}
echo json_encode($data);
$mysqli->close();
?>
I would like an output looking something like
"nameOfArray":[{object},{object},{object}]
Weird thing is, I had ik working properly using old methods, which I removed (Being quite stupid, honestly)
So hopefully someone here can point me in the right direction. Thanks a lot in advance.
Edit: When I do a print_r, I see the data, so it has to do with encoding it to json, the mysql bit is coorect. I also found some answers using a jsonSerializer, but I just can't imagine it needs to be so difficult when it used to be quite easy.
Upvotes: 1
Views: 657
Reputation: 1055
although the question is old but may help others falling in similar problem. This is a common mistake when u change your mysql code to mysqli code. you dint passed the connection variable on procedural calling mysqli_fetch_assoc() . something like this will work.
<?php
$mysqli = new mysqli("$host", "$username", "$password","$db_name");
$myQuery = "SELECT * FROM myTable ORDER BY date DESC LIMIT 4";
$result = $mysqli->query($myQuery);
$data = array();
while($row = mysqli_fetch_assoc($mysqli, $result)) {
$data['nameOfArray'][] = $row;
}
echo json_encode($data);
$mysqli->close();
?>
Upvotes: 0
Reputation: 9635
try this
<?php
$mysqli = new mysqli("$host", "$username", "$password","$db_name");
$myQuery = "SELECT * FROM myTable ORDER BY date DESC LIMIT 4";
$result = $mysqli->query($myQuery);
$data = array();
while($row = $result->fetch_assoc()) {
$data['nameOfArray'][] = $row;
}
echo json_encode($data);
$mysqli->close();
?>
Upvotes: 1