Call to a member function close() on null [duplicate] - php

This question already has answers here:
Fatal error: Call to a member function close() on a non-object. MySQLi issue
(3 answers)
Closed 4 years ago.
Doing a user creation page for a school project.
The code worked perfectly fine when using localhost, but gave the title’s error upon uploading it to a web host.
The error is on the the “$stmt->close();” which I believe is not being called, but not sure why it works internally on my system.
<?php
/* entering localhost config instead
require_once "config.php";
*/
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'users');
$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
$sql = "SELECT id FROM users WHERE username = ?";
if($stmt = $mysqli->prepare($sql)){
$stmt->bind_param("s", $param_username);
$param_username = trim($_POST["username"]);
if($stmt->execute()){
$stmt->store_result();
if($stmt->num_rows == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Something went wrong.";
}
}
$stmt->close();
}
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
if($stmt = $mysqli->prepare($sql)){
$stmt->bind_param("ss", $param_username, $param_password);
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT);
if($stmt->execute()){
header("location: login.php");
} else{
echo "Something went wrong.";
}
}
$stmt->close();
}
$mysqli->close();
}
?>
Solved
Dumb error
Used
declare(strict_types=1);
error_reporting(-1);
ini_set('display_errors', 'true');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
to find that it was simply a character error in the db config file. Sorry to waste your time.
By the way - The passwords are hashed in the database.

You wrote: if($stmt = $mysqli->prepare($sql)){
If the condition does not match $sdmtp will ne null so your $stmt->close(); will fail.
move the line $stmt->close(); into your if execution block.
The other problem you are facing is your confusion about the fact that your code does produce this error on the dev-system (the non-localhost one). This migth be caused by an exception in $mysqli->prepare($sql) on the dev-system.

Related

Mysql bind: number of elements do not match

I can't fathom where I went wrong on this instruction. I keep getting the warning that number of elements does not match the bind value.
I'm trying to validate a field for country where users can select the country they are registering from but whenever I run a test on xampp I get the warning whilst the information aren't sent to the database.
I'm not sure if my code is liable to sql injections since I'm new to php and mysql. If i remove the country function the form works properly. I think the error is from the html form so I'd rather not uploaded it here.
Here's the php code.
<?php
// Include config file
require_once "db.php";
// Define variables and initialize with empty values
$username = $password = $confirm_password = $country = "";
$username_err = $password_err = $confirm_password_err = $country_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM users WHERE username = ?";
if($stmt = mysqli_prepare($db, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Validate password
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Validate Country
if(empty(trim($_POST["country"]))){
$country_err = "Please Choose a Country.";
}
else{
$country = trim($_POST["country"]);
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO users (username, password, country) VALUES (?, ?, ?)";
if($stmt = mysqli_prepare($db, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password, $param_country);
// Set parameters
$param_country = $country;
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: login.php");
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($db);
}
?>.`
I can see a couple of things:
Your check for input errors does not check if "country_err" is empty.
Your mysqli_stmt_bind_param only defines types for 2 fields, "ss", but you are passing in 3 fields so it should be "sss"

Data is not showing up in database after "succesful" registration [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
Hey so I've followed a tutorial on how to create a functional registration system with php and all the code seems to work just fine, however the data I input in my registration form doesn't show up in my database even though the script gives me the output that I have successfully registered. Does anyone know a solution to this?
<?php
// Connect to the db
$DATABASE_HOST = 'localhost';
$DATABSE_USER = 'root';
$DATABSE_PASS = '';
$DATABSE_NAME = 'phplogin';
// Try to connect
$con = mysqli_connect($DATABASE_HOST, $DATABSE_USER, $DATABSE_PASS, $DATABSE_NAME);
if(mysqli_connect_errno()) {
//If there is an error stop the script and display the error
exit('Failed to connect to MySQL: '. mysqli_connect_error());
}
//check if the data already exists
if (!isset($_POST['username'], $_POST['password'], $_POST['email'])) {
//Could not get the data that should have been sent
exit('Please register first');
}
//Submitted registration values are not empty
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['email'])) {
//if empty exit the script
exit('Please complete the register form');
}
//check if the username has been used already
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
//encrypt password
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
//store the results to be able to check the db
if ($stmt->num_rows > 0) {
//username already exists
echo 'Username already used';
} else {
//Insert new account
if ($stmt = $con->prepare('INSERT INTO accounts (username, password, email) VALUES (?, ?, ?)')) {
//hash the password and use password_verify
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt->bind_param('sss', $_POST['username'], $password, $POST['email']);
$stmt->execute();
echo 'You have succesfully registered, you can now login';
}}
$stmt->close();
} else {
//Something wrong with the sql statement
echo 'Could not prepare Statement!';
}
$con->close();
?>
It is very good practise to add error checking to your code when developing. An easy way to this is to add this at the top of your php page inside php code tags to at least echo errors out on your page -
error_reporting(E_ALL);
ini_set('display_errors', 1);
Your code should look like this, should return a record. If you had error reporting on, it would have told you where the errors are -
// Connect to the db
$DATABASE_HOST = 'localhost';
$DATABSE_USER = 'root';
$DATABSE_PASS = '';
$DATABSE_NAME = 'phplogin';
// Try to connect
$con = mysqli_connect($DATABASE_HOST, $DATABSE_USER, $DATABSE_PASS, $DATABSE_NAME);
if(mysqli_connect_errno()) {
//If there is an error stop the script and display the error
exit('Failed to connect to MySQL: '. mysqli_connect_error());
}
//check if the data already exists
if (!isset($_POST['username']) || !isset(['password']) || !isset($_POST['email'])) {
//Could not get the data that should have been sent
exit('Please register first');
} else {
//check if the username has been used already
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
//encrypt password
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
//username already exists
echo 'Username already used';
} else {
//Insert new account
if ($stmt = $con->prepare('INSERT INTO accounts (username, password, email) VALUES (?, ?, ?)')) {
//hash the password and use password_verify
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt->bind_param('sss', $_POST['username'], $password, $POST['email']);
$stmt->execute();
echo 'You have succesfully registered, you can now login';
} else {
echo 'Data not inserted...';
}
}
$stmt->close();
}
$con->close();

Get FALSE value when I insert data into mysql database

When I just insert the username and password into my sql database, everything is okay but I get FALSE value when I try to add user's full name and company. I am not sure whether the way I bind variables to the prepared statement as parameters is correct or not. Can anyone please help me have a look on my code ? Thanks in advance!
<?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $full_name = $company = $password = $confirm_password = "";
$username_err = $full_name_err = $company_err =$password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Validate full name
if(empty(trim($_POST["full_name"]))){
$full_name_err = "Please enter your full name.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM users WHERE full_name = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_full_name);
// Set parameters
$param_full_name = trim($_POST["full_name"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$full_name_err = "The name is already taken.";
} else{
$full_name = trim($_POST["full_name"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Validate company
if(empty(trim($_POST["company"]))){
$company_err = "Please enter your company.";
} else{ $company = trim($_POST["company"]);}
// Validate password
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 2){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)&& empty($full_name_err)&& empty($company_err)){
// Prepare an insert statement
$sql = "INSERT INTO users (username,full_name, company, password) VALUES (?,?,?,?)";
if($stmt = mysqli_prepare($link, $sql)){
// Set parameters
$param_username = $username;
$param_full_name = $full_name;
$param_company = $company;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ssss", $param_username,$param_full_name,$param_company, $param_password);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: login.php");
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
}
?>

Can't login (PHP & MySQL)

I'm making a complete login system. The register part works just fine but if I try to login, I just get a white screen. No errors, no redirects,... The php code does execute since my url changes to 'login.php'. I tried multiple ways to make a login, but that dind't work either.
Thanks in advance!
<?php
session_start();
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: index_afterlogin.html");
exit;
}
require_once "config.php";
$email = $password = "";
$email_err = $password_err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty(trim($_POST["email"]))){
$email_err = "Please enter e-mail.";
} else{
$email = trim($_POST["email"]);
}
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
if(empty($email_err) && empty($password_err)){
$sql = "SELECT userID, email, password FROM users WHERE email = ?";
if($stmt = mysqli_prepare($db, $sql)){
mysqli_stmt_bind_param($stmt, "s", $param_email);
$param_email = $email;
if(mysqli_stmt_execute($stmt)){
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
mysqli_stmt_bind_result($stmt, $id, $email, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["userID"] = $id;
$_SESSION["email"] = $email;
header("location: index_afterlogin.html");
} else{
$password_err = "The password you entered was not valid.";
}
}
} else{
$email_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
mysqli_stmt_close($stmt);
}
mysqli_close($db);
}
?>

When submitting a form I receive my error but not sure why

Why do I seem to receive my echo statement "error" when submitting this form?
I got this code from https://www.tutorialrepublic.com/php-tutorial/php-mysql-login-system.php for register.php.
It was working fine for my users up till yesterday and can't seem to find why?
I thought maybe it was my config.php but it does print the error message if a username is already in use so it doesn't seem to be config.php. I messaged the website that I got the code from and they couldn't help me.
<?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM sign_in_account WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Validate password
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO sign_in_account (username, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: login.php");
} else{
echo "Something went wrong. Please try again later. error: 1";//Error 1 = form submission
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
The output should go to my login.php page on successful result submission but prints my echo statement "echo "Something went wrong. Please try again later. error: 1";"

Categories