// Set the database credentials $host = 'localhost'; $dbname = 'my_database'; $username = 'my_username'; $password = 'my_password'; // Connect to the database try { $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }
// Prepare the query $stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id'); // Bind the parameter $stmt->bindParam(':id', $id); // Execute the query $stmt->execute(); // Fetch the results $results = $stmt->fetch(PDO::FETCH_ASSOC);
// Prepare the query $stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)'); // Bind the parameters $stmt->bindParam(':name', $name); $stmt->bindParam(':email', $email); // Set the values of the parameters $name = 'John Doe'; $email = 'john@example.com'; // Execute the query $stmt->execute();These examples use the PDO library that is included with PHP by default.