I am probably at the “low intermediate” level in procedural PHP, but my only experience with OOP PHP was a project done in class about five years ago and I want to re-learn and become more proficient in OOP PHP.
Yesterday I worked through an OOP tutorial that built a simple registration system. The only problem was that it was a bit out of date and used mysql_. I tried to convert to mysqli_ but am running into problems that I can’t figure out how to fix.
Here is the relevant code from the database class (DB.class.php) -
<?php
// DB.class.php
class DB {
protected $db_name = 'databasename';
protected $db_user = 'databaseuser';
protected $db_pass = 'databasepassword';
protected $db_host = 'databasehost';
// Open a connect to the database.
// Make sure this is called on every page that needs to use the database.
public function connect() {
$connect_db = new mysqli( $this->db_host, $this->db_user, $this->db_pass, $this->db_name );
if ( mysqli_connect_errno() ) {
printf("Connection failed: %s\
", mysqli_connect_error());
exit();
}
return true;
}
}
And in the userTools.class.php file there is (I just included here an example of a method that is causing problems) :
<?php
// UserTools.class.php
require_once 'User.class.php';
require_once 'DB.class.php';
class UserTools {
// Log the user in.
// First check to see if the username and password match a row in the database.
// If it is successful, set the session varialbes and store the user object within.
public function login( $username, $password ) {
$hashedPassword = md5($password);
$result = mysqli_query("SELECT * FROM users WHERE username = '$username' AND password = '$hashedPassword' ");
if ( mysqli_num_rows($result) == 1 ) {
$_SESSION[ "user" ] = serialize( new User( mysqli_fetch_assoc( $result ) ) );
$_SESSION[ 'login_time' ] = time();
$_SESSION[ 'logged_in' ] = 1;
return true;
} else {
return false;
}
}
}
I am getting the error message (among many): “mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\OOBusiness\classes\UserTools.class.php on line 42”.
I have tried all sorts of things to fix this issue, but nothing seems to work. What else do I need to change/add in my switch from mysql to mysqli?