$servername = "localhost";
$username= "root";
$password = "";
$dbname = "registration_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) { die("Connection failed: " . $conn-
>connect_error); }
$user = $_POST['username’];
$email = $_POST['email’];
$pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, email, password) VALUES
('$user', '$email', '$pass')";
if ($conn->query($sql) === TRUE) { echo "Registration successful!"; }
else { echo "Error: " . $sql . "<br>" . $conn->error; }
$conn->close(); ?>
What does this code do?
• Used to register a new user into a
database.
• It takes the username, email, and
password from a form and
• Saves them in a database called
registration_db.
3.
1. Connect tothe Database
What’s happening here?
These lines set up the connection to
the database.
•localhost means the database is on
the same computer.
•root is the username to access the
database.
•"" means there’s no password (it’s
left blank).
•registration_db is the name of the
database where user information will
be stored.
4.
2. Create aDatabase Connection
What’s happening here?
This line creates a connection to the database
using the information above.
3. Check if the Connection Works
What’s happening here?
If the connection fails, it will show an error
message and stop the program.
5.
4. Get theData from the Form
What’s happening here?
•$_POST['username']: Gets the username entered in the form.
•$_POST['email']: Gets the email entered in the form.
•$_POST['password']: Gets the password entered in the form.
•password_hash(): This function turns the password into a secure
format that cannot be easily guessed (for security).
6.
5. Write theSQL Command to Add the Data
What’s happening here?
•This line creates a command to insert the username, email, and
password into a table called users.
•The users table should have columns named username, email, and
password.
7.
6. Run theSQL Command
What’s happening here?
• If the data is successfully added to the database, the message "Registration
successful!" will be displayed.
• If there’s a problem, an error message will be shown, explaining what went
wrong.
8.
7. Close theDatabase Connection
What’s happening here?
This line closes the connection to the database to free up
resources.