I am trying to learn OOP in php, and so I decided to have a go at creating a simple login script. The following code works fine; it logs me in as required. However, the database connection is held within the function, which means that every time I want to access the database I have to log in again. Not great!
I have tried to set up a connection class but I cannot seem to find a way to reference the connection within the function. Can anyone help please. P.s. I have had a look at other answers but cannot seem to find anything that helps.
public function test_login($username,$password){
[B]$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_errno()) {
printf("Failed to connect to MySQLi: %s\n", mysqli_connect_errno());
}[/B]else{
/* Set up and execute prepared statment to retrieve User id */
$query ="SELECT uid from users WHERE username='$username' and password = '$password'";
/* create a prepared statement */
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute(); /* execute query */
$stmt->bind_result($uid); /* bind result variables */
/* fetch value */
if($stmt->fetch()){
$_SESSION['login'] = true;
$_SESSION['uid'] = $uid;
return TRUE;
}else{
return FALSE;
}
$stmt->close(); /* close statement */
}
/* close connection */
$mysqli->close();
}
}
Thanks in advance!