本文實例講述了PHP的簡單PDO操作。分享給大家供大家參考,具體如下:
網(wǎng)上關(guān)于PDO的資料很多。這里就不累贅了。
這里我將PDO所有操作封裝到一個類里方便操作。
類代碼如下:
class DB {
//pdo對象
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();
}
}
使用方法:
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 的表類型 InnoDB(支持事務(wù)) MyISAM(不支持事務(wù))
echo $db->con->rollBack();
throw new MyException("事務(wù)測試錯誤", $e);
}
$db = NULL;
PDO支持SQL語句以參數(shù)方式調(diào)用,可有效的防止SQL注入。
希望本文所述對大家PHP程序設(shè)計有所幫助。