This article describes the simple PDO operation of PHP. Share to everyone for your reference, specific as follows:
There are a lot of information about PDO online. It's not a burden here.
Here I will PDO all operations into a class for ease of operation.
The class code is as follows:
Class DB {
//pdo object public
$con = NULL;
function DB ()
{
$this->con = new PDO ("Mysql:host=127.0.0.1;dbname=dbtest", "root", "xxx", Array (
PDO:: Mysql_attr_init_command => ' SET NAMES ' UTF8 ',
pdo::attr_persistent TRUE,
));
$this->con->setattribute (Pdo::attr_errmode, pdo::errmode_exception);
$this->con->setattribute (Pdo::attr_case, pdo::case_upper);
Public Function query ($sql, $para = NULL)
{
$sqlType = Strtoupper (substr ($sql, 0, 6));
$cmd = $this->con->prepare ($sql);
if ($para!= NULL)
{
$cmd->execute ($para);
}
else
{
$cmd->execute ();
}
if ($sqlType = = "Select")
{return
$cmd->fetchall ();
}
if ($sqlType = = "INSERT")
{return
$this->con->lastinsertid ();
}
return $cmd->rowcount ();
}
How to use:
Include "pdo.php";
$db = new db ();
$subjectList = $db->query ("select * from ' table1 '");
$count = $db->query ("UPDATE ' table1 ' SET ' name ' = ' Test ' WHERE ' id ' =: id", Array (': Id ' => 795));
Try
{
echo $db->con->begintransaction ();
$count = $db->con->exec ("UPDATE" table1 ' SET ' name ' = ' test1 ' WHERE ' id ' = 795 ');
$count = $db->con->exec ("UPDATE" table1 ' SET ' name1 ' = ' test22 ' WHERE ' id ' = 795 ');
$count = $db->con->exec ("UPDATE" table1 ' SET ' name1 ' = ' test333 ' WHERE ' id ' = 795 ');
echo $db->con->commit ();
}
catch (Exception $e)
{
//MYSQL table type InnoDB (Support transaction) MyISAM (does not support transactions)
echo $db->con->rollback ();
throw new MyException ("Transaction test Error", $e);
}
$db = NULL;
PDO supports SQL statements to be invoked as parameters, effectively preventing SQL injection.
More interested in PHP related content readers can view the site topics: "PHP Network Programming Skills Summary", "PHP basic Grammar Introductory Course", "PHP operation Office Document Skills Summary (including word,excel,access,ppt)", " PHP Date and Time usage summary, PHP Introduction to object-oriented Programming, PHP String (String) Usage summary, PHP+MYSQL database Operations Tutorial and PHP Common database operating Skills summary
I hope this article will help you with the PHP program design.