Monday, June 25, 2018

php - Uncaught Error: Call to a member function query() on null



I got stuck for hours in the code below. I don't know how I can fix this error.




Notice: Undefined variable: mysqli in D:\xampp\htdocs\recon\register.php on line 19



Fatal error: Uncaught Error: Call to a member function query() on null in D:\xampp\htdocs\recon\register.php:19 Stack trace: #0 {main} thrown in D:\xampp\htdocs\recon\register.php on line 19






$conn = new mysqli('localhost', 'root', '', 'user');

if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}


$uname = $_POST['uname'];
$psw = $_POST['psw'];
$options = [
'cost' => 12,];
$hashedpassword= password_hash($psw, PASSWORD_BCRYPT, $options);

$result = $mysqli->query("SELECT username FROM registration WHERE username = '$uname'");
$row_count = $result->num_rows;
if($row_count == 1) {

echo 'User already exists, try another one.'; }
else {

$query = "INSERT INTO user (username, password) VALUES(?, ?)";
$statement = $mysqli->prepare($query);

$statement->bind_param('ss', $uname, $hashedpassword);

if($statement->execute())
{

print 'Success! Last inserted record : ' .$statement->insert_id .'
';
}
else
{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();

}


?>

Answer



You are declaring instance of mysqli called $conn. This represents your connection to DB. You should call methods on variable $conn and not on (undefined) variable $mysqli. So ie. your line 19 should be:



$result = $conn->query("SELECT username FROM registration WHERE username = '$uname'")


Also to prevent SQL-Injection on your queries/web-pages you should use prepared statements EVERYWHERE(including SELECT).


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...