在非对象上调用成员函数fetch_object()

时间:2012-09-23 13:06:03

标签: php

当我加载包含下面代码的PHP页面时,我得到错误“在非对象上调用成员函数fetch_object()”。它属于以while开头的行。为什么会出现此错误? 请忽略我的安全漏洞。

PHP代码段:

header('Content-Type:application/json;charset=utf-8');

$file_absolute = "---placeholder for correct file path---";
include_once($file_absolute);
$mysql = new mysqli($db_host, $db_username, $db_password, $db_name);
$verb_value = $_POST['verb_value'];

$mysql->query("SET CHARACTER SET 'utf8'");

$result = $mysql->query("SELECT present_tense FROM $verb_value");

$queryResult = array();

while ($row = $result->fetch_object())
{
    $queryResult[] = $row->present_tense;
}

2 个答案:

答案 0 :(得分:7)

您的代码中缺少错误检查:

$result = $mysql->query("SELECT present_tense FROM $verb_value");
if( !$result)
  die($mysql->error);

$queryResult = array();

while ($row = $result->fetch_object())
{
    $queryResult[] = $row->present_tense;
}

您的查询结果是非对象,但您没有检查它。

注意:您的代码容易出现SQL注入:$verb_value = $_POST['verb_value']导致可以将SQL代码注入数据库而无需检查!

答案 1 :(得分:0)

$verb_value = $_POST['verb_value'];

$mysql = new mysqli($db_host, $db_username, $db_password, $db_name);

$mysql->query("SET CHARACTER SET 'utf8'");

if (mysqli_connect_errno()) {
       printf("Connect failed: %s\n", mysqli_connect_error());
       exit();
    }
$query = "SELECT present_tense FROM $verb_value";
$queryResult = array();
if ($result = $mysql->query($query)) {
  while ($row = $result->fetch_object()) {
     $queryResult[]=$row->present_tense;
  }
  $result->close();
 }