Example Php Register Code

Example Php Register Code

·

2 min read

<?php
// Include your database connection file
include('db_connection.php');

// Initialize variables to store user input
$username = "";
$email = "";
$password = "";
$confirm_password = "";

// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Retrieve user input from the form
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];

    // Validate input (you may want to add more validation)
    if (empty($username) || empty($email) || empty($password) || empty($confirm_password)) {
        echo "All fields are required";
    } elseif ($password !== $confirm_password) {
        echo "Password and confirm password do not match";
    } else {
        // Hash the password (you should use a more secure hashing method in a real application)
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

        // Insert user data into the database (make sure to use prepared statements to prevent SQL injection)
        $sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sss", $username, $email, $hashed_password);

        if ($stmt->execute()) {
            echo "Registration successful";
        } else {
            echo "Error: " . $stmt->error;
        }

        // Close the statement and database connection
        $stmt->close();
        $conn->close();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Registration</title>
</head>
<body>

    <h2>User Registration</h2>

    <form method="post" action="">
        <label for="username">Username:</label>
        <input type="text" name="username" value="<?php echo $username; ?>" required>

        <br>

        <label for="email">Email:</label>
        <input type="email" name="email" value="<?php echo $email; ?>" required>

        <br>

        <label for="password">Password:</label>
        <input type="password" name="password" required>

        <br>

        <label for="confirm_password">Confirm Password:</label>
        <input type="password" name="confirm_password" required>

        <br>

        <button type="submit">Register</button>
    </form>

</body>
</html>

In this example, replace 'db_connection.php' with the file that contains your database connection details (e.g., host, username, password, and database name). Also, ensure that you have a table named 'users' in your database with columns 'username', 'email', and 'password'.