【发布时间】:2014-07-04 10:42:08
【问题描述】:
我的域上有 mysql 数据库在线,我有一个名为“Locations”的简单表,其中包含一些数据,我想调用数组中的数据,然后用 json 对数组进行编码,最后回显编码的 json 数据。这是我的代码,我的问题是将数据放入数组并将其编码为jso:
<?php
// obtaining connection : successful!
$con = mysql_connect("myhost", "username", "password");
$con or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
// selecting all from table "locations" : successful!
$result = mysql_query("SELECT * FROM Locations")
or die(mysql_error());
// puting data into array and encode it with json : FAILED!
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
// closing connection : successful!
mysql_close($con);
?>
我运行我的代码,得到的结果如下:
谢谢你们。
已编辑:
我换成了mysqli,现在是这样的:
<?php
// Create connection
$con=mysqli_connect("host","user","pass","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM Locations";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($result);
mysqli_close($con);
?>
仍然得到完全相同的错误
【问题讨论】:
-
这是一个 500 服务器错误.. 你检查过你的日志吗/另外注意,你不应该使用 mysql_ 你应该升级到 mysqli_
-
您使用的是an obsolete database API,应该使用modern replacement。
-
什么是循环中的 $result 变量? ...
-
我认为你应该使用
$data而不是$result -
我将 $data 编辑为 $result,还是同样的问题
标签: php mysql json database encode