php 在非对象上调用成员函数 fetch_assoc()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2840765/
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_assoc() on a non-object
提问by Joann
Here's my function:
这是我的功能:
function get_fname($un){
$registerquery = $this->conn->query("SELECT f_name FROM tz_members WHERE
usr='".$un."'");
while ($row = $registerquery->fetch_assoc()) {
return $fname = $row[$un];
}
}
Edit:
编辑:
I chose to answer my own question because it has an editor.
我选择回答我自己的问题,因为它有一个编辑器。
@Mark Baker:
@马克贝克:
<?php
require_once 'Mysql.php';
$mysql = new Mysql();
?>
<html>
<head>
</head>
<body>
<h4><?php echo $mysql->get_fname("joann"); ?></h4>
</body>
</html>
That's how I am doing it...
我就是这样做的...
回答by Gumbo
It seems that your query failed. Because in that case queryreturns false. So try this:
您的查询似乎失败了。因为在这种情况下query返回false。所以试试这个:
$registerquery = $this->conn->query("SELECT f_name FROM tz_members WHERE
usr='".$un."'");
if ($registerquery) {
while ($row = $registerquery->fetch_assoc()) {
return $fname = $row[$un];
}
}
The failure may be caused by a syntax error in your query when $uncontains characters that break the string declaration (like 'or \). You should use MySQLi::real_escape_stringto escape that characters to prevent that.
当$un包含破坏字符串声明的字符(如'或\)时,查询中的语法错误可能会导致失败。您应该使用MySQLi::real_escape_string来转义该字符以防止出现这种情况。
Additionally, a function can only return a value once. So the whilewill be aborted after the first row.
此外,一个函数只能返回一个值一次。所以while将在第一行之后中止。
回答by Mark Baker
$fname = $row[$un]; is assigning the value in $row[$un] to the variable $fname, then returning the result. It's pointless doing that assignment to $fname because $fname is simply a local variable within the function.... if it's defined as global, then it's not good programming practise.
$fname = $row[$un]; 将 $row[$un] 中的值赋给变量 $fname,然后返回结果。对 $fname 进行赋值是没有意义的,因为 $fname 只是函数内的一个局部变量......如果它被定义为全局变量,那么它就不是好的编程实践。
If echo $mysql->get_fname("joann") is the line where you're calling the get_fname() function, then how are you setting $mysql?
如果 echo $mysql->get_fname("joann") 是您调用 get_fname() 函数的行,那么您如何设置 $mysql?
And what do you think will happen if the database query doesn't find any valid result for the query?
如果数据库查询没有找到任何有效的查询结果,您认为会发生什么?
回答by Sven van den Boogaart
Is it possible you forgot to give a table name in the connection?
您是否可能忘记在连接中提供表名?
$conn = new mysqli('localhost', 'root', 'password', 'ANY VALUE HERE??');
$conn = new mysqli('localhost', 'root', 'password', 'ANY VALUE HERE??');
回答by sundowatch
while ($row = fetch_assoc($registerquery)) {
return $fname = $row[$un];
}
}

