Google News
logo
Select data with PDO (+ Prepared statements) in PHP
In the following example of PHP program that demonstrates selecting data with PDO and prepared statements in PHP :
Program :
<?php

// Database connection settings
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'myusername';
$password = 'mypassword';

// Create a PDO instance
try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Prepare a SQL statement with a parameter
$stmt = $pdo->prepare("SELECT * FROM mytable WHERE id = :id");

// Bind a value to the parameter
$id = 1;
$stmt->bindParam(':id', $id);

// Execute the statement
$stmt->execute();

// Fetch the result as an associative array
$result = $stmt->fetch(PDO::FETCH_ASSOC);

// Output the result
echo "<table>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
echo "<tr><td>" . $result['id'] . "</td><td>" . $result['name'] . "</td><td>" . $result['email'] . "</td></tr>";
echo "</table>";

// Close the database connection
$pdo = null;
?>
This program connects to a MySQL database using PDO, prepares a SQL statement with a parameter, binds a value to the parameter, executes the statement, and fetches the result as an associative array.

It then outputs the result in an HTML table. Finally, it closes the database connection.