php 在非对象上调用成员函数 fetch_object()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12552588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call to a member function fetch_object() on a non-object
提问by programm3r
When I load the PHP page containing the code below I get the error "Call to a member function fetch_object() on a non-object." It pertains to the line starting with the word while. Why is this error popping up? Ignore my security weaknesses please.
当我加载包含以下代码的 PHP 页面时,出现错误“调用非对象上的成员函数 fetch_object()”。它与以单词 while 开头的行有关。为什么会弹出这个错误?请忽略我的安全弱点。
PHP snippet:
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;
}
回答by JvdBerg
You are lacking error checking in your code:
您的代码中缺少错误检查:
$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;
}
The result of your query is a non object, but you did not check for that.
您的查询结果是一个非对象,但您没有检查它。
Note: your code is prone to SQL Injection: $verb_value = $_POST['verb_value']results in a possibility to inject SQL code into the database without checking!
注意:您的代码很容易发生 SQL 注入:$verb_value = $_POST['verb_value']导致有可能在不检查的情况下将 SQL 代码注入到数据库中!
回答by Afshin
$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();
}

