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.