What are alternative methods for password hashing and database interactions in PHP, such as using PDO with prepared statements and password_hash()?
When storing passwords in a database, it is crucial to hash them securely to protect user data. One common method to achieve this in PHP is by using the password_hash() function to hash passwords before storing them. Additionally, using PDO with prepared statements can help prevent SQL injection attacks when interacting with the database.
// Connect to the database using PDO
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement to insert a new user with a hashed password
$stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
// Hash the password using password_hash()
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
// Bind parameters and execute the statement
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':password', $password);
$stmt->execute();