PHP,Mysql

PDO预处理查询

和MySQLi的预处理查询类似,首先我们要准备一个模板

$sql = "insert into user (name,age) VALUES (?,?);";
$stmt=$pdo->prepare($sql);

然后就是绑定参数,这一步有些不同,我们需要使用 bindValue 绑定参数的顺序和参数的值,不需要规定值的类型

$stmt->bindValue(1,'lisi');
$stmt->bindValue(2,20);

然后执行

$stmt->execute();

完整代码如下

<?php

$dsn = "mysql:host=localhost;dbname=lianxi;port=3306;charset=utf8";
$user = "root";
$pwd = "123456";

$pdo = new PDO($dsn, $user, $pwd);

$sql = "insert into user (name,age) VALUES (?,?);";
$stmt = $pdo->prepare($sql);

$stmt->bindValue(1, 'lisi');
$stmt->bindValue(2, 20);

$stmt->execute();

除此之外,PDO提供了一张更简单的方法,可以在execute当中直接传入数组作为参数,索引数组的键对应着参数顺序

<?php

$dsn = "mysql:host=localhost;dbname=lianxi;port=3306;charset=utf8";
$user = "root";
$pwd = "123456";

$pdo = new PDO($dsn, $user, $pwd);

$sql = "insert into user (name,age) VALUES (?,?);";
$stmt = $pdo->prepare($sql);

$stmt->execute(['lisi',20]);
微信扫一扫,向我赞赏

微信扫一扫,向我赞赏

微信扫一扫,向我赞赏

支付宝扫一扫,向我赞赏

回复

This is just a placeholder img.