To execute raw SQL queries with PDO in PHP, you can follow these steps:
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
prepare()
method of the PDO object. Pass your raw SQL query as a parameter to the prepare()
method. For example:$sql = 'SELECT * FROM mytable WHERE id = :id';
$stmt = $pdo->prepare($sql);
bindParam()
or bindValue()
methods. Parameters can be used to prevent SQL injection. For example:$id = 1;
$stmt->bindParam(':id', $id, PDO::PARAM_INT); // bind $id as an integer parameter
execute()
method. For example:$stmt->execute();
fetch()
, fetchAll()
, or fetchColumn()
methods. For example:$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
Remember to handle any errors that may occur during the execution of the query using try-catch statements or PDO error handling functions.