How to execute raw SQL queries with PDO in PHP?

To execute raw SQL queries with PDO in PHP, you can follow these steps:

  1. Establish a database connection using PDO by creating an instance of the PDO class. Pass the database credentials as parameters to the PDO constructor. For example:
$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(); }
  1. Prepare the SQL query using the 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);
  1. Bind any parameters if necessary using the 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
  1. Execute the prepared statement using the execute() method. For example:
$stmt->execute();
  1. Fetch the data from the executed statement using the 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.