【问题标题】:How to convert an object of class mysqli_result to a json object如何将类 mysqli_result 的对象转换为 json 对象
【发布时间】:2017-05-07 15:11:26
【问题描述】:

使用下面的 php 代码,我试图从我的数据库中选择一条记录。当我运行代码时出现此错误:

可捕获的致命错误:不能是类 mysqli_result 的对象 转成字符串

我想要实现的是将结果转换为 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;


?>

【问题讨论】:

标签: php mysql json


【解决方案1】:

您需要遍历结果,因为 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 将行作为键控数组返回 - 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) like:

$var = mysqli_real_escape_string($con,$_GET['name']);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2023-03-17
    • 2014-05-17
    • 2017-12-27
    相关资源
    最近更新 更多