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