2017-05-07 230 views
0

通過下面的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; 


?> 
+0

您的代碼很容易受到[** 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)。 –

回答

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返回行作爲keyd array - http://php.net/manual/en/mysqli-result.fetch-assoc.php

至於SQL注入防禦,請使用mysqli_real_escape_stringhttp://php.net/manual/en/mysqli.real-escape-string.php),如:

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