l202/nah2.php

<?php // SQLite database setup (create a file named "database.db" in the same directory) $database = new SQLite3('database.db'); // Create a users table if it doesn't exist $database->exec('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE, password TEXT)'); // Initialize variables for error handling $usernameError = $passwordError = $registrationError = ""; // Check if the form is submitted if ($_SERVER["REQUEST_METHOD"] == "POST") { // Get user input $enteredUsername = $_POST["username"]; $enteredPassword = $_POST["password"]; // Validate username if (empty($enteredUsername)) { $usernameError = "Please enter your username."; } // Validate password if (empty($enteredPassword)) { $passwordError = "Please enter your password."; } // If username and password are entered, attempt registration if (!empty($enteredUsername) && !empty($enteredPassword)) { // Hash the password before storing it $hashedPassword = password_hash($enteredPassword, PASSWORD_DEFAULT); // Insert user data into the database $query = $database->prepare('INSERT INTO users (username, password) VALUES (:username, :password)'); $query->bindValue(':username', $enteredUsername, SQLITE3_TEXT); $query->bindValue(':password', $hashedPassword, SQLITE3_TEXT); $result = $query->execute(); if ($result) { // Redirect to a success page or perform other actions header("Location: page2.php"); exit(); } else { // Display registration error $registrationError = "Username already exists. Please choose a different username."; } } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sign Up with SQLite Database</title> </head> <body> <h2>Sign Up</h2> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <p> <label for="username">Username:</label> <input type="text" name="username" id="username" value="<?php echo isset($_POST['username']) ? $_POST['username'] : ''; ?>"> <span style="color: red;"><?php echo $usernameError; ?></span> </p> <p> <label for="password">Password:</label> <input type="password" name="password" id="password"> <span style="color: red;"><?php echo $passwordError; ?></span> </p> <p> <span style="color: red;"><?php echo $registrationError; ?></span> </p> <p> <input type="submit" value="Sign Up"> </p> </form> </body> </html>

Resultaat

Made by Thijs Aarnoudse