Ouch, if you are a new learner to PHP (which it seems to be as you have asked ChatGPT without understanding the code), you are going down a rabbit hole very fast. Rather learn from proper material where the code is explained and you understand why and where you use what code, classes, statements etc., as an example -
Prepared statements and stored procedures [
^]
To use your generated code to avoid the error, your call to the connection to close is in the wrong place which is why you get the error -
<?php
include 'connect.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$query = "INSERT INTO register (name, email, password) VALUES ('$name', '$email', '$hashed_password')";
if ($conn) {
if ($conn->query($query) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: ". $query. "<br>". $conn->error;
}
$conn->close();
} else {
echo "Error: Unable to connect to the database";
}
}
?>
Now, adding to OriginalGriff's and Pete's solutions, the correct way is to use parameterized queries as per the link given, else you will be in more trouble than expected with hackers and some other nasty monsters out there... -
Prepared statements as below help prevent SQL injection attacks and provide a cleaner way to execute your SQL queries -
Without seeing your coonect.php code, the following will suffice -
<?php
$servername = "your_servername";
$username = "your_username";
$password = "your_password";
$database = "your_database";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->set_charset("utf8mb4");
?>
To understand UTF-8 and why to se it, see -
PHP and Unicode: Handling Multilingual Text and UTF-8[
^]
The code to use now would look similar to the following -
<?php
include 'connect.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$query = "INSERT INTO register (name, email, password) VALUES (?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->bind_param("sss", $name, $email, $hashed_password);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
$stmt->close();
}
$conn->close();
?>
As a last tip, use CHATGPT as an indicator and not as the true gospel, you will be finding yourself on the same lonely island time after time. You do however need to understand what code it feeds you to actually use that code in your project, rather than dumping some code and asking to fix the errors...