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.
Yeah I think there is an issue with the query but I cant find where.
You are using mysqli wrong way. 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. 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.
Because of that
$db->query("SELECT * FROM `$table_name` WHERE `username` = '$username'");
returns value FALSE and hence you're getting the error/warning.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.