<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// Set PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Insert query with placeholders
$sql = "INSERT INTO users (name, email, password) VALUES (:name, :email, :password)";
// Prepare statement
$stmt = $conn->prepare($sql);
// Bind parameters
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
// Values to insert
$name = "John Doe";
$email = "john@example.com";
$password = "123456";
// Execute the query
$stmt->execute();
// Get last inserted ID
echo "New record inserted successfully. Last inserted ID is: " . $conn->lastInsertId();
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Close connection
$conn = null;
?>