Skip to main content

PDO in PHP

What is PDO:


PDO has a much nicer interface and more productive,PDO also has different drivers for different SQL database. PDO is enabled by default in PHP installations now,  however you need two extensions to be able to use PDO: PDO, and a driver for the database you want to use like pdo_mysql. Installing the MySQL driver is as simple as installing the php-mysql package in most distributions.


Connections are established by creating instances of the PDO base class and you always use the PDO class name.


If there are any connection errors, a PDOException object will be thrown. You may catch the exception if you want to handle the error condition, or you may opt to leave it for an application global exception handler that you set up via set_exception_handler().


Download link :


https://drive.google.com/open?id=0BxmTZPVcu72fMVVCcVE1cEw1c1E


Exception handling :


<?php
     try {
           $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
  
       } catch (PDOException $e) {
       print "Error!: " . $e->getMessage() . "<br/>";
        die();
   }
?>


New ways to connection between database and php following ways :


<?php
       $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>


Running Simple Select Statements


Please follow the following step to connect database and execute simple select statement :


1-connection.php


2-home.php


connection.php file put following code :


Code:


<?php
/*
* Start:: Database connection::-
*/
$hostname="localhost";
$username="root";
$password="";
$dbname="testPDO";


try {
$db = new PDO("mysql:host=$hostname;dbname=$dbname;charset=utf8mb4", $username, $password);
}
catch (PDOException $e) {
       print "Error!: " . $e->getMessage() . "<br/>";
        die();
   }
/*
* End:: Database connection::-
*/
?>


Above connection file make that connect mysql server if the connection is not created then loop goes to exception handling  and send error message using getMessage function


home.php


Code :


<?php
/*
*include connection file and fetch if you want record::-
*/
include('connection.php');


$stmt = $db->query('SELECT * FROM tbl_sh_user');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);


echo '<pre>';
print_r($results);
echo '</pre>';
die();


?>


Above home.php file include connection file connection.php and write simple select statement to fetch data from particular table


Following simple operation using PDO method


1-Insert :


<?php


$result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', Disuza)");
$insertId = $db->lastInsertId();


?>


2-update :


<?php
$results = mysql_query("UPDATE table SET field='value'") or die(mysql_error());
$affected_rows = mysql_affected_rows($result);
echo $affected_rows.' were affected';
?>


3-Delete :


<?php
$stmt = $db->prepare("DELETE FROM table WHERE id=:id");
$stmt->bindValue(':id', $id, PDO::PARAM_STR);
$stmt->execute();
$affected_rows = $stmt->rowCount();
?>



Comments

Popular posts from this blog

using PDO database connection add,update,delete,edit operation

PDO advantage : 1-Object Oriented 2-Bind parameters in statements (security) 3-Allows for prepared statements and rollback functionality (consistency) 4-Throws catcheable exceptions for better error handling (quality) 5-Exception mode; no need to check error state after each API call. It's best to tell PDO how you'd like the data to be fetched. You have the following options: 1-PDO::FETCH_ASSOC: returns an array indexed by column name. 2-PDO::FETCH_BOTH: (default):returns an array indexed by both column name and number. 3-PDO::FETCH_BOUND:Assigns the values of your columns to the variables set with the ->bindColumn() method. 4-PDO::FETCH_CLASS: Assigns the values of your columns to properties of the named class. It will create the properties if matching properties do not exist. 5-PDO::FETCH_INTO:Updates an existing instance of the named class. 6-PDO::FETCH_LAZY: Combines. 7-PDO::FETCH_BOTH/PDO:FETCH_OBJ, creating the object variable names as t...

Profile Share Fixing the Thumbnail Image, Title and Description for Shared Links

Profile Share Fixing the Thumbnail Image, Title and Description for Shared Links user want to share any information then use following code  and read step by step Profile Share Fixing the Thumbnail Image, Title and Description for Shared Links if you want share profile on following social link : 1-Facebook 2-twitter.com 3-LinkedIn 4-google +, Code link : https://drive.google.com/open?id=1IzTZZh_0euDqFSHL_vPRiQePlNTw3h-q Demo link : http://freeteachnology.hol.es/socialshare/ To modify a page's thumbnail image, description, and additional metadata for these services, you can provide meta tags in the HTML code of the page.Implementing Open Graph Meta Tags You can implement meta tags in a number of ways. In content management systems might  be allow you to modify a page's meta tags , then use following code in meta section of your project code, <link href="bootstrap.min.css" rel="stylesheet"> <link href="bootstrap-tour.m...

GUID for globally unique identifier

How to create GUID in php 1-guid stands for globally unique identifier generally used to create random unique strings in php, create access token in php 2-Mostly use of GUID for generating access token, generate unique id, generating unique string in php. Using this article how to create guide in php you can create a random string for any use to keep unique 3-GUID consists of alphanumeric characters only and is grouped in five groups separated by hyphens as seen in this example: 3F2504E0-4F89-11D3-9A0C-0305E82C3301 Eg:- <?php /** * Generate Globally Unique Identifier (GUID) * E.g. 2EF40F5A-ADE8-5AE3-2491-85CA5CBD6EA7 * * @param boolean $include_braces Set to true if the final guid needs * to be wrapped in curly braces * @return string */ function generateGuid($include_braces = false) { if (function_exists('com_create_guid')) { if ($include_braces === true) { return com_create_guid(); } else { return substr(com_cr...