Reputation: 363
I have just come back to a project that was working fine a month ago. Today I have found im getting a "Warning: mysqli::query(): Couldn't fetch mysqli" error and I have no idea why. I have tried changing the if statement but I still get the same result.
php page
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
error_reporting(E_ALL); ini_set('display_errors', 1);
$email = $_SESSION['email'];
$name = $_SESSION['name'];
$hash = $_SESSION['hash'];
$password = $hash;
echo $name;
echo '<br>';
echo $email;
echo '<br>';
echo $hash;
echo '<br>';
$sql = "INSERT INTO signed_up(`name`, `email`, `password`) VALUES ('$name', '$email', '$password')";
if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
//if ($result = $mysqli->query("INSERT INTO `signed_up`(`name`, `email`, `password`) VALUES ('$name', '$email', '$password')")){
//
//header('location: ../register_success.php');
//// $result->close();
//
//}
//else {
// echo "error";
//}
?>
The error im getting
you have succesfuly connected to the database
gptgeoff
$2y$10$JUi/eSNwbTnM4ZyWetEL6.ELSepLPKLkEiJdi4WYMyp/sEEAk9hKe
Warning: mysqli::query(): Couldn't fetch mysqli in /home/sites/unitest.co.uk/public_html/includes/register_user.inc.php on line 24 Warning: main(): Couldn't fetch mysqli in /home/sites/unitest.co.uk/public_html/includes/register_user.inc.php on line 27 Error: INSERT INTO signed_up(name
, email
, password
) VALUES ('gptgeoff', '[email protected]', '$2y$10$JUi/eSNwbTnM4ZyWetEL6.ELSepLPKLkEiJdi4WYMyp/sEEAk9hKe')
The db_connect.php file works because I'm getting the "you have succesfuly connected to the database" displaying, the session variables are being passed and echoed out in both the echo statements and in the values of the $sql query so I am unable to understand why this has stopped working, can anyone advice please
db_connect.php
<?php
include_once 'psl-config.php'; // As functions.php is not included
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if(!$mysqli) {
die('error connecting to database');
}
echo 'you have succesfuly connected to the database'.'<br/><br/>';
?>
Upvotes: 2
Views: 157
Reputation: 33276
This line:
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
creates an object. It is an instance of the class mysqli
. An object will always be true. Your if statement checks if $mysqli
is false. This if statement is wrong, because whether the connection was successful or not the object will never be false.
Do not check for connection errors manually. Your connection failed and when it did PHP threw a warning. Please check your PHP configuration for error reporting, because you have probably warnings silenced. Also please enable mysqli error reporting. Insert this line before creating an instance of mysqli.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
Upvotes: 0