PDO using Prepared Statements a Complete Reference Guide

PDO using Prepared Statements a Complete Reference Guide

In this post we will show you PDO using Prepared Statements One of the normal error made by novice level PHP designers is utilization of the old uncertain mysql augmentation to interface with MySQL database. This prompts intense security vulnerabilities like SQL Injection in their sites. I am not accusing junior engineers since I MYSELF do a similar oversight in my first site. The fundamental explanation behind this is albeit official PHP documentation is to a great degree institutionalized it is a wreck for amateurs such a large number of starters go for the old unstandardized blog for referral and wind up with using age old unstandardized codes.

PDO using Prepared Statements : I know by and by numerous designers who still utilize censured mysql expansion rather than new enhanced mysqli augmentation or PDO permits you to get to the usefulness gave by MySQL 4.1 or more. This is the principle motivation behind why I am making this instructional exercise so that any novice who begins their programming in PHP can utilize new database free interface for getting to databases in PHP. To guarantee most extreme security and to forestall SQL Injection assaults I am using Prepared Statements and Bind parameters in this instructional exercise however believe me I attempt to make this one as basic as could reasonably be expected.

What is PDO using Prepared Statements?

PDO using Prepared Statements remains for PHP Data Objects which is a lightweight, steady interface for getting to databases in PHP. Dissimilar to mysqli interface, it is database autonomous so in the event that you learn PDO you can change to any database in future. Anyway, i am not going to portray all points of interest of it in this instructional exercise which is outside of any relevant connection to the issue at hand and superfluous.

Why Prepared Statements and Bind Parameters?

The PDO with Prepared articulations and Bind Parameters is to expel noxious code from the client info and therefore to keep us from SQL Injection. Restricting datatype to client include using tie parameter guarantee that lone indicated datatype with determined length is acknowledged. It guarantees that assailants can’t embed string datatype in fields which just require whole number qualities.

Presently Let’s begin coding.

Associating with Database :: PDO using Prepared Statements

Before we begin associating with our database we have to build up the association with the database. If there should be an occurrence of PDO you have to make one question for every database you might want to interface with. Here is the punctuation for that.

$database_conn = new PDO('mysql:host=$database_host;port=5432;dbname=$database_name', $database_user, $database_pass);

For effortlessness and code reusability we will incorporate all code for association foundation inside a connect.php record and incorporate this document in all PHP pages which require database operation by using require 'connect.php'; explanation toward the start of the page. The entire code for connect.php record is given beneath.

<?php
					
$database_host = 'localhost'; // database host name    
$database_user = 'database_user'; // database user name
$database_pass = 'database_password'; // database user password
$database_name = 'your_database_name'; // database name


try{
    $database_conn = new PDO('mysql:host=$database_host;port=5432;dbname=$database_name', $database_user, $database_pass); 
    $database_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
	// exception for PDO connection error
	$database_conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);  
	// sql injection protection for get maximum result
    // echo "successfully Connected to DB.";
} 
catch(PDOException $exception){
    // error in database connection
    echo "Could not connect to database : " . $exception->getMessage(); 
	// exception
}

Note: For improvement/taking in, it’s a smart thought to set the PDO mistake mode characteristic PDO::ERRMODE_EXCEPTION. This will toss a special case if there is a blunder. We should likewise set the PDO::EMULATE_PREPARES to false to forestall SQL Injection assaults. I likewise indicate the port number in the association code which is not required in the event that you are using localhost but rather you have to determine it on the off chance that you are interfacing with some remote generation condition with various settings. As a matter of course, the MySQL port number is 3306.

Recovering all Results :: PDO using Prepared Statements

So as to recover all information from database in PDO with no where condition, we can basically utilize query() technique rather than secure get ready explanations since we are not tolerating any client input which may bring about SQL Injection assaults. The punctuation for query() technique is given beneath.

$pdo_query = $db->query(QUERY);

Presently we should take a gander at the total code for a specimen record work which brings 8 mytables subtle elements from mytable table.

function index()
{
	global $database_conn;

	$pdo_query = $database_conn->query("SELECT title,prices,authors FROM mytable ORDER BY prices DESC LIMIT 85");

	$results = $pdo_query->fetchAll();

	echo "<b>Index Page</b> ( Total No of Results : ".$pdo_query->rowCount()." )</br>";
	foreach($results as $object_val)
	{
		echo "</br>Title : ".$object_val['title']."</br>Auther : ".$object_val['authors']."</br> prices : ".$object_val['prices']."</br>";	 
	}
}

The fetchAll() strategy is utilized to bring all outcomes. In the event that you have just a single column then you can utilize fetch() technique. The fetchAll() strategy and fetch() technique return comes about as an acquainted exhibit design as a matter of course. I utilized foreach explanation for getting each column.

You can utilize $pdo_query->rowCount() technique to get the check of the quantity of columns.

Geting a single values :: PDO using Prepared Statements

Geting a single values with PDO using Prepared Statements :: Insertion Here we will utilize arranged explanation with tie parameters since there is a where condition in our inquiry which acknowledge client input esteem. The code for an example demonstrate work which recovers a mytable with a particular mytable id and name is given underneath.

function show_row($id,$title)
{
	global $database_conn;
	
	$pdo_query = $database_conn->prepare('SELECT title,prices,authors  FROM mytable WHERE bookid = ? AND title = ?');
		
	$pdo_query->bindParam(1, $id, PDO::PARAM_INT);
    $pdo_query->bindParam(2, $title, PDO::PARAM_STR, 21);
	
	$pdo_query->execute();

	$result_val = $pdo_query->fetch();

	echo "</br><b>Show Page</b></br>";
	
    echo "</br>Title : ".$result_val['title']."</br>Auther : ".$result_val['authors']."</br> Price : ".$result_val['prices']."</br>";	 
	
}

Note: Here I utilized the bindParam function to guarantee that id acknowledges just number esteem and length of title must not more noteworthy than 21 characters.

The yield picture of over two function is given underneath.

PDO Prepare articulation shareurcodes

Insertion :: PDO using Prepared Statements

InsertionThe Insertion code additionally requires arranged explanations and tie parameters since it is tolerating client input. The entire code for embed function is given underneath.

function insert_row($title,$author,$price)
{
	global $database_conn;
	
	$pdo_query = $database_conn->prepare('INSERT INTO mytable (title,authors,prices) VALUES (?, ?, ?)');

	$pdo_query->bindParam(1,$title, PDO::PARAM_STR, 51);
	$pdo_query->bindParam(2,$authors, PDO::PARAM_STR, 26);
	$pdo_query->bindParam(3,$prices, PDO::PARAM_INT);

	$pdo_query->execute();
   
   
}

Note: If you are putting away value then likely you think need to store it as decimal esteem then you have to store it as string as bindParam function did not bolster decimal qualities.

Updation :: PDO using Prepared Statements

Updation PDO using Prepared Statements :: The total code for refresh function is given underneath.

function delete_row($title)
{
	global $database_conn;
	
	$pdo_query = $database_conn->prepare('DELETE FROM mytable WHERE title = ?');

	$pdo_query->bindParam(1,$title, PDO::PARAM_STR, 53);

	$pdo_query->execute();
   
}

Deletion :: PDO using Prepared Statements

Deletion PDO using Prepared Statements :: The total code for delete function is given underneath.

function delete_row($title)
{
	global $database_conn;
	
	$pdo_query = $database_conn->prepare('DELETE FROM mytable WHERE title = ?');

	$pdo_query->bindParam(1,$title, PDO::PARAM_STR, 53);

	$pdo_query->execute();
   
}

You also like google recaptcha using javascript and google recaptcha using php

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  3  =  9

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US