Click here to Skip to main content
15,901,205 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
<?php
// Include the database connection file
include 'connect.php';

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $name = $_POST['name']; // Assuming you have a field with name 'name' in your form
    $email = $_POST['email']; // Assuming you have a field with name 'email' in your form
    $password = $_POST['password']; // Assuming you have a field with name 'password' in your form

    // Hash the password before storing it in the database
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Add data to the database
    $query = "INSERT INTO register (name, email, password) VALUES ('$name', '$email', '$hashed_password')";

    // Check if the connection to the database was successful
    if ($conn) {
        // Check if the query was successful
        if ($conn->query($query) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: ". $query. "<br>". $conn->error;
        }
    } else {
        echo "Error: Unable to connect to the database";
    }
}

// Close the database connection
// $conn->close(); // Remove this line to avoid the error
?>


What I have tried:

Connected successfully
Fatal error: Uncaught Error: mysqli object is already closed in C:\xampp\htdocs\website project\add.php:21 Stack trace: #0 C:\xampp\htdocs\website project\add.php(21): mysqli->query('INSERT INTO reg...') #1 {main} thrown in C:\xampp\htdocs\website project\add.php on line 21
Posted

Start by reading the error message - it gives you a lot of information.

Look at this: How to Write Code to Solve a Problem, A Beginner's Guide Part 2: Syntax Errors[^] - it's primarily about syntax errors, but the error message format is pretty much identical.

In this case, your error ius on line 21 of the file add.php which is this code:
PHP
if ($conn->query($query) === TRUE) {
and it's saying that your connection is closed - so you need to look at when it gets opened which is in code we cannot see.

Additionally, you are making bigger mistakes!

1) Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

2) Never store passwords in clear text - it is a major security risk. There is some information on how to do it here: Password Storage: How to do it.[^]

And remember: if you have any European Union users then GDPR applies and that means you need to handle passwords as sensitive data and store them in a safe and secure manner. Text is neither of those and the fines can be .... um ... outstanding. In December 2018 a German company received a relatively low fine of €20,000 for just that.
 
Share this answer
 
To add to OriginalGriff's excellent answer, you should have been able to figure out the solution to this yourself through debugging. Debugging is a fundamental skill that every developer should master because it's the way to find the solution to most bugs.

Think of it this way. Suppose your car breaks down. Posting here on CodeProject is the equivalent of ringing the garage and saying that you have a problem with your car. You tell them that there's a knocking sound under the bonnet. The mechanic may suggest a few things it could be; that's the equivalent of us suggesting areas that you need to look at.

Now, imagine if you knew how to fix a car yourself. You attach a diagnostic utility to your engine management system and it reports that you have a low oil level. Congratulations, you have just diagnosed what the problem is yourself, and you can work out what you need to do (safely add oil). Well, debugging is the diagnostic equivalent in software development.
 
Share this answer
 
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
<?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;
        }

        //You need to close the databse connection here, not outside of your IF statement...
        $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
<?php
//Add your database credentials here...
$servername = "your_servername";
$username = "your_username";
$password = "your_password";
$database = "your_database";

//Create your connection...
$conn = new mysqli($servername, $username, $password, $database);

//Check if your connection is successful...
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

//Set the charset to UTF-8...
$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
<?php
//Include your connection file - connect.php...
include 'connect.php';

//First check if your form has been submitted...
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    //Get the data submitted...
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    //Using your code and which is way outside the scope of this question, hash the password before storing it in your database, you need to read up much more on salted passwords, proper hashing etc...
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    //Now prepare and bind your query...
    $query = "INSERT INTO register (name, email, password) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("sss", $name, $email, $hashed_password);

    //When done, execute your query...
    if ($stmt->execute()) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $query . "<br>" . $conn->error;
    }

    //Now close the statement, NOT outside of the IF block otherwise you will get the same error...
    $stmt->close();
}

//Now you can close the database connection...
$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...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900