Hi! 🙂
I just started a new project and I decided I would try doing it with Object-Oriented PHP instead of Procedural. I learned the basics, and I started off writing a small piece of code to retrieve user information from a database. Though, I am receiving an error that I don't really understand, and I still don't believe the code is as efficient as it could be for what I want to do.
Here it is:
<?php
$mysqli = new mysqli('localhost', 'PRIVATE', 'PRIVATE', 'PRIVATE');
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
class user {
var $id;
var $username;
//when using, type (referring to input) can either be 'id' or 'username'
//input is either the user id or username, depending on which you picked for the type
public function __construct($input, $type) {
if ($type == 'username') {
$sql = 'SELECT * FROM users WHERE username = '.$input;
$res = $mysqli->query($sql);
$row = $res->fetch_array();
$this->id = $row["id"];
$this->username = $input;
} else if($type = 'id') {
}
}
public function id() {
return $this->id;
}
public function username() {
return $this->username;
}
}
$user = new user('test', 'username');
echo $user->id();
?>
And I received the following error:
Fatal error: Call to a member function query() on a non-object in tng/common.php on line 19
Line 19 being:
$res = $mysqli->query($sql);
Any help is highly appreciated.