Question:
How can I replace outdated mysql_* functions with PDO and prepared statements to securely store and retrieve data from a database?
Answer:
$hostname = '*host*'; $username = '*user*'; $password = '*pass*'; $database = '*database*'; $dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$username = $_POST['username']; $email = $_POST['email']; $stmt = $dbh->prepare("INSERT INTO `users` (username, email) VALUES (?, ?)"); $stmt->bindParam(1, $username, PDO::PARAM_STR); $stmt->bindParam(2, $email, PDO::PARAM_STR); $stmt->execute();
The length parameter is not required for PDO::PARAM_STR. However, if you have a maximum character limit for the field in your database table, you can specify it after PDO::PARAM_STR as shown below:
$stmt->bindParam(1, $username, PDO::PARAM_STR, 255);
$user_id = $_GET['id']; $stmt = $dbh->prepare("SELECT * FROM `users` WHERE `id` = ?"); $stmt->bindParam(1, $user_id, PDO::PARAM_INT);
The above is the detailed content of How to Replace Outdated `mysql_*` Functions with PDO and Prepared Statements for Secure Database Interactions?. For more information, please follow other related articles on the PHP Chinese website!