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