我有一个包含多行的表,我想用json对所有行进行编码。
我一直在寻找其他问题和解决方案,我尝试了很多不同的方法,但json_encode仍然返回null
<?php
$mysqli = new mysqli('localhost', 'root', 'password', 'testBasParmak');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sth = mysql_query("SELECT * FROM pictures");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
$error = json_last_error();
print $error;
$mysqli->close();
?>
终端输出
[]0
如果我试试这个
$sth = mysql_query("SELECT * FROM pictures");
$rows = array("id" => $id,"name" => $name,"description" => $description,"url" => $url,"users_id" => $users_id,"users_id" => $users_id,"totalvoteup" => $totalvoteup,"totalvotedown" => $totalvotedown,"totalvoteneutral" => $totalvoteneutral);
while($r = mysql_fetch_assoc($sth)) {
$row[] = $r;
}
print json_encode($rows);
$error = json_last_error();
print $error;
终端输出
{"id":null,"name":null,"description":null,"url":null,"users_id":null,"totalvoteup":null,"totalvotedown":null,"totalvoteneutral":null}0
也许它没有发送正确的查询?
答案 0 :(得分:3)
$row[] = $r;
应该是
$rows[] = $r;
答案 1 :(得分:0)
最后我发现答案我的数据库连接是mysqli,但我对SELECT *
的查询是mysql所有我需要改变的是mysql命令到mysqli
$sth = $mysqli->query("SELECT * FROM pictures");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[]=$r;
}
print json_encode($rows);
给出正确的输出
["id":"2","name":"Jess","description":"who","url":"www","users_id":"705735067","totalvoteup":"0","totalvotedown":"0","totalvoteneutral":"0"},{"id":"3","name":"Jess","description":"who","url":"www","users_id":"705735067","totalvoteup":"0","totalvotedown":"0","totalvoteneutral":"0"},{"id":"4","name":"Jess","description":"who","url":"www","users_id":"705735067","totalvoteup":"0","totalvotedown":"0","totalvoteneutral":"0"}]