PDO with INSERT INTO through prepared statements

To insert data into a database using PDO and prepared statements, you can use the following steps:

  1. Connect to the database using PDO.
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
  1. Prepare the SQL statement. This creates a prepared statement and returns a PDOStatement object.
$stmt = $dbh->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
  1. Bind the values to the parameters in the prepared statement. This specifies the values for the parameters in the prepared statement.
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
  1. Execute the prepared statement. This inserts the data into the database.
$stmt->execute();

Watch a course Learn object oriented PHP

Here is an example of the complete code:

<?php

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmt = $dbh->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->execute();

This code assumes that you have already established a connection to the database and that you have a valid PDO object stored in the $dbh variable. It also assumes that you have defined the variables $name and $email, which contain the values that you want to insert into the database.