Please Like our Facebook Page

Introduction to PHP MySQL prepared statements using PDO


With PHP, you can connect and manipulate databases using PHP MySQL prepared statements. Under this walkthrough, we are going to learn how to use PHP MySQL prepared statements in PDO. PDO stands for PHP DATA OBJECT, where it’s used to execute SQL prepared statements with high efficiency.

Introduction to MySQL Prepared Statements using PDO

As we have seen in the introductory part of this article, PDO prepared statements are used to execute SQL statements with high efficiency hence reducing risks associated with SQL injection. Now the question arises, How do PDO prepared statements prevent SQL Injection? Well, it’s NOT PDO that prevents you from SQL-injections, its prepared statements. You can use PDO without using its prepared statements and also other extensions (MySQLi, SQLite3, …) support them too.

Also Check:How to use SQL LIKE Clause in A PDO Prepared Statement



How to Connect to MySQL Database using PDO

Before we get into details of PHP MySQL prepared statements, let’s first understand how to connect to MySQL database using PDO. The following code indicates how to connect to MySQL database using PDO

<?php

$severName = "localhost";
$db_name = "pdo";
$db_username = "root";
$db_password = "";

try{
	$con = new PDO("mysql:host=$severName; dbname=$db_name", $db_username, $db_password);
	$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	
	
} catch (PDOException $e){
	die($e->getMessage());
}

Understanding how to connect to MySQL database using PDO

Connecting to MySQL database requires you to understand four things, namely: Sever Name, Datbase name, Database username and database password. try and catch block is used to handle exception, just in case something goes wrong such as wrong database username or anything else. To understand more about everything in the code above, kindly watch this video on YouTube:



Video on how to connect to mysql database using PDO










Please Like us on Facebook