我正在学习使用json的rest api并通过json数组检索值。我正在尝试请求本地主机数据库。此表包含两个值id和status这两列都有整数值。
这是我的请求
http://localhost/webservice_mine.php?ID='1'&Status='2'
我得到的错误是
可捕获的致命错误:mysqli_result类的对象无法在第24行的c:\wamp\www\webservice_mine.php中转换为字符串
我认为这是因为我正在向sql查询传递一个整型变量。连接变量时出错吗?有人能解释一下怎么做吗?那将是很大的帮助。
<?php
if((isset($_REQUEST["ID"]))&&(isset($_REQUEST["Status"]))){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "arduino_test";
$jsonarray= array('Status' => false,'Message'=>"Empty" );
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
$jsonarray= array('Status' => false,'Message'=>"Database Not Connected" );
echo json_encode($jsonarray);
}
else{
$jsonarray= array('Status'=>false,'Message'=>"Database connected" );
$sql = "SELECT * FROM `lights` WHERE ID=".$_REQUEST["ID"]."";
//$result = $conn->query($sql);
$result = $conn->query($sql);
echo $result;
$jsonarray= array('Status'=>false,'Message'=> $result );
if (($result = $conn->query($sql)) !== FALSE)
{
echo "query success";
while($row = $result->fetch_assoc())
{
echo "ID: " . $row["ID"]. " ";
}
}
else
{
echo "query failure";
echo "Error: " . $sql . "<br>" . $conn->error;
}
// output data of each row
//while($row = $result->fetch_assoc()) {
//$jsonarray[] = $row;
//}
echo json_encode($jsonarray);
}
}
?>
最佳答案
(对不起英语不好)
$jsonarray= array('Status'=>false,'Message'=> $result );
$result
是资源,而不是数组$data = array(); //empty array
while($row = $result->fetch_assoc())
{
$data[] = $row; //store each row in $data
}
$jsonarray= array('Status'=>false,'Message'=> $data );
您可以使用:
$data = $result->fetch_all(MYSQLI_ASSOC);
//fetch all data from resource and return as associative array
而不是:
$data = array(); //empty array
while($row = $result->fetch_assoc())
{
$data[] = $row; //store each row in $data
}
结果相同,但代码更少:)