PDO INSERT prepared statement
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database_name = "database_name";
// CREATE DATABASE CONNECTION USING PDO METHOD
try {
$database_connection = new PDO("mysql:host=$servername;dbname=$database_name", $username, $password);
// Set the PDO error mode to exception
$database_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection Failed" . $e->getMessage();
}
// INSERT DATA INTO THE DATABASE
try {
$sql = "INSERT INTO `users` (first_name, last_name, email) VALUES (?,?,?)";
$stmt = $database_connection->prepare($sql);
$stmt->bindParam(1, $first_name, PDO::PARAM_STR);
$stmt->bindParam(2, $last_name, PDO::PARAM_STR);
$stmt->bindParam(3, $email, PDO::PARAM_STR);
// Assigning data into the variables
$first_name = 'John';
$last_name = 'Doe';
$email = '[email protected]';
$stmt->execute();
echo "Data inserted successfully";
} catch (PDOException $e) {
echo "data not inserted";
}
?>