I have the following code:
function user_name($id) {
$eqpt_name1 = $this->sql->query("SELECT `f_val` FROM `profiles` WHERE `u_id` = $id AND `f_id` = 1");
$eqpt_name1_2 = $eqpt_name1->fetch();
$name1 = $eqpt_name1_2['f_val'];
$eqpt_name2 = $this->sql->query("SELECT `f_val` FROM `profiles` WHERE `u_id` = $id AND `f_id` = 2");
$eqpt_name2_2 = $eqpt_name2->fetch();
$name2 = $eqpt_name2_2['f_val'];
$name3 = $name1 . " " . $name2;
return $name3;
}
what it does is take the provided user id ($id) and gets the First ($name1) and Last ($name2) name of the user and then outputs it.
I call it by doing the following
$username = user_name($_SESSION['user_id']);
$_SESSION['user_id'] is 1, for example.
When I manually put the code in a PHP file, it works fine. But when I use a function so I can use it globally over the entire site so I don’t have to have that long query code on every page, Apache gives me this error:
PHP Fatal error: Call to a member function query() on a non-object
I’ve never written a function that has a query in it before and not sure what I am doing wrong.
Judging by how you’re calling it, that’s just a global function;
$thiswon’t be defined, and so you can’t use$this->sql. If you have a global variable called$sql, tell PHP that you’re using it:Also, you’re using PDO, so why aren’t you using prepared statements? And you can simplify things a little further, too: