如何将类mysqli_result的对象转换为json对象
问题描述:
通过下面的php代码,我试图从数据库中选择一条记录。当我运行的代码,我得到这个错误:如何将类mysqli_result的对象转换为json对象
Catchable fatal error: Object of class mysqli_result could not be converted to string
我想实现的是将结果转换成JSON对象,而是我得到这个错误。
<?php
session_start();
include_once 'db/dbconnect.php';
$var = $_GET['name'];
// echo $var;
$json = [];
$sql = "SELECT * from recipes WHERE recipes.recipeName = '.$var'";
$rslt = mysqli_query($con,$sql);
echo $rslt;
?>
答
你需要遍历的结果,因为mysqli的一次返回一行:
$sql = "SELECT * from recipes WHERE recipes.recipeName = '$var'";
$rslt = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($rslt)){
print_r($row);
}
,或者到JSON它:
$json = array();
while($row = mysqli_fetch_assoc($rslt)){
$json[] = $row;
}
echo json_encode($json);
mysqli_fetch_assoc
返回行作为keyd array - http://php.net/manual/en/mysqli-result.fetch-assoc.php
至于SQL注入防御,请使用mysqli_real_escape_string
(http://php.net/manual/en/mysqli.real-escape-string.php),如:
$var = mysqli_real_escape_string($con,$_GET['name']);
您的代码很容易受到[** SQL注入**](https://en.wikipedia.org/wiki/SQL_injection)攻击。你应该使用[** mysqli **](https://secure.php.net/manual/en/mysqli.prepare.php)或[** PDO **](https://secure.php.net/ manual/en/pdo.prepared-statements.php)准备带有绑定参数的语句,如[**这篇文章**]所述(https://stackoverflow.com/questions/60174/how-can-i-prevent-sql步喷射功能于PHP)。 –