[英]Notice: Trying to get property of non-object
I've built a table in which users register ads.我建立了一个表格,用户可以在其中注册广告。 Everyone who submits an ad becomes the owner of that ad.
提交广告的每个人都成为该广告的所有者。 So now I try to get all information related to those ads by providing the username who is the owner.
所以现在我尝试通过提供所有者的用户名来获取与这些广告相关的所有信息。
I've build this funciton:我已经建立了这个功能:
function get_ad_info_by_username($username,$table_name) {
$ad_info = array();
$db = new mysqli("localhost", "root", "", "bazar-rooz") or die ('db connection issue!');
$query = $db->query("SELECT * FROM `$table_name` WHERE `username` = '$username'");
$db->query("set names 'UTF8'");
if ($query->num_rows) { // here I get the error ... property of non-object
while ($row = $query->fetch_object()) {
$ad_info[] = $row;
}
}
return $ad_info;
}
I've used the same structure in other functions to get different information.我在其他函数中使用了相同的结构来获取不同的信息。 They work fine but this one gives error all the time when I try to run the page to show ads information to the end user.
它们工作正常,但是当我尝试运行页面以向最终用户显示广告信息时,这个总是出错。
faintsignal: it's actually not an error.微弱信号:这实际上不是错误。 It's just a notice but the query doesn't return any rows anyway.
这只是一个通知,但查询无论如何都不会返回任何行。 It says:
它说:
Notice: Trying to get property of non-object in C:\\wamp\\www\\site\\functions\\functions.php on line 261 line 261 is the line I've commented inside the code.
注意:尝试获取 C:\\wamp\\www\\site\\functions\\functions.php 中第 261 行第 261 行中非对象的属性是我在代码中注释的行。
Yeah I think there is an issue with the query but I cant find where.是的,我认为查询有问题,但我找不到在哪里。
You are using mysqli wrong way.您正在以错误的方式使用 mysqli。 In many wrong ways to be honest.
在许多错误的方式上说实话。
However, as with raw mysqli it will take too much extra code, I will show you the proper way using PDO.但是,与原始 mysqli 一样,它会占用太多额外的代码,我将向您展示使用 PDO 的正确方法。 Nevertheless, all the below guidelines are common for the both drivers:
尽管如此,以下所有准则对于这两个驱动程序都是通用的:
here it goes在这里
$dsn = "mysql:host=localhost;dbname=bazar-rooz;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'root','', $opt);
function get_ad_info_by_username($username)
{
global $pdo;
$stmt = $pdo->prepare("SELECT * FROM table_name WHERE `username` = ?");
$stmt->execute([$username]);
return $stmt->fetchAll();
}
$ads = get_ad_info_by_username('joe');
May be the tablename you are passing to function可能是您传递给函数的表名
get_ad_info_by_username($username,$table_name)
is either wrong or does not exist in database. get_ad_info_by_username($username,$table_name)
错误或数据库中不存在。
Because of that正因为如此
$db->query("SELECT * FROM `$table_name` WHERE `username` = '$username'");
returns value FALSE and hence you're getting the error/warning.返回值 FALSE,因此您收到错误/警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.