I'm really confused to what is the proper way of interfacing with a database from inside a class, I know I'm doing it wrong below, but I still would've expected it to work at least?
class User{
public function user_email($user_id){
require_once("config/db.php");
$finduser = $db->query("SELECT email FROM `user` WHERE user_id = '".$user_id."' ");
$user_data = $finduser->fetch_assoc();
return $user_data["email"];
}
}
And then I am using the code below to display the result on another page, this first instance works fine, but the second throws an error.
<?php echo $user->user_email($user_id); ?>
<?php echo $user->user_email($user_id); ?>
Notice: Undefined variable: db on line 89
Fatal error: Call to a member function query() on a non-object on line 89
So what I'm basically asking is, what would be a good way of interfacing to a database from a class where the connection to the database is in one location?
Thanks for your help!
require_once, it will only be required once. Changerequire_oncetorequireand the script will always be loaded by any subsequent call of the methoduser_email.