php pdo 查看,一些PHP+PDO的查询技巧

1,类似PHP框架中的预处理,简单理解为可绑定参数自动传值

This example fetches data based on a key value supplied by a form. The user input is automatically quoted, so there is no risk of a SQL injection attack.

这个例子里获取的数据,根据用户提交的表单自动生成,不需要程序员判断变量,用户提交的数据将被自动转义,所有没有SQL注入的问题

[php]

$stmt = $dbh->prepare("SELECT * FROM users where name = ?");

if ($stmt->execute(array($_GET['name']))) {

while ($row = $stmt->fetch()) {

print_r($row);

}

}

?>

[/php]

2,同上,自动赋值的另外一种代码样式

[php]

$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");

$stmt->bindParam(1, $name);

$stmt->bindParam(2, $value);

// insert one row

$name = 'one';

$value = 1;

$stmt->execute();

// insert another row with different values

$name = 'two';

$value = 2;

$stmt->execute();

?>

[/php]

3,PHP+PDO+Mysql

[php]

try {

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

foreach ($dbh->query('SELECT * from FOO') as $row) {

print_r($row);

}

$dbh = null;

} catch (PDOException $e) {

print "Error!: " . $e->getMessage() . "
";

die();

}

?>

[/php]

4,完善的事务处理功能

[php]

try {

$dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',

array(PDO::ATTR_PERSISTENT => true));

echo "Connected\n";

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$dbh->beginTransaction();

$dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");

$dbh->exec("insert into salarychange (id, amount, changedate)

values (23, 50000, NOW())");

$dbh->commit();

} catch (Exception $e) {

$dbh->rollBack();

echo "Failed: " . $e->getMessage();

}

?>

[/php]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值