本文实例讲述了php的简单pdo操作。分享给大家供大家参考,具体如下:
网上关于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(支持事务) myisam(不支持事务)
echo $db->con->rollback();
throw new myexception("事务测试错误", $e);
}
$db = null;
pdo支持sql语句以参数方式调用,可有效的防止sql注入。
更多关于php相关内容感兴趣的读者可查看本站专题:《php网络编程技巧总结》、《php基本语法入门教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!