Connecting To MYSQL With PDO

Connecting To mySQL Using PDO

Although there are several methods you can use to connect to a mySQL database, the PDO(PHP Data Objects) method is a very good technique. For one, it is universal and can be used with Sqlite databases since it does not use any commands specific to mySQL. In addition to being universal, you can use PDO prepared statements to avoid the need to escape mySQL strings since bindParam method can do that for you.

Below is a simple example that shows how to connect to the database and make an insert statement. Other mySQL commands like Select, Update and Delete can be used by replacing the command that is shown below.

$user = '<username>';
$pass = "<add_password_here>";
$dbh = new PDO('mysql:host=localhost;dbname=username_database', $user, $pass);


$emailaddr = $_POST['email'];


$command = "INSERT INTO clients (id,email,date2) VALUES (NULL, :email, now())";
$command2 = $dbh->prepare($command);

//$command2->bindParam(':id', $myid);
$command2->bindParam(':email', $emailaddr);
//$command2->bindParam(':date2', $mydate);
$command2->execute();

//or

/*
$command2->execute(array(
    ':id'    => $myid,
    ':email' => $emailaddr,
    ':date2' => $mydate
));*/