In PHP authentication systems, how do I store results in a database?

When developing an authentication system in PHP, you typically need to store user credentials such as usernames and passwords securely in a database. Below is an example demonstrating how to handle user registration and store the results in a MySQL database using PHP's PDO extension.

<?php // Database connection settings $host = 'localhost'; $db = 'your_database_name'; $user = 'your_username'; $pass = 'your_password'; try { // Create a new PDO instance $pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Example user data $username = 'exampleUser'; $password = 'examplePassword'; // Hash the password $hashedPassword = password_hash($password, PASSWORD_DEFAULT); // Prepare an SQL statement $stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (:username, :password)"); // Bind parameters $stmt->bindParam(':username', $username); $stmt->bindParam(':password', $hashedPassword); // Execute the statement $stmt->execute(); echo 'User registered successfully!'; } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } ?>

PHP Authentication User Registration MySQL PDO Password Hashing