PHP之PDO的使用

pdo方式连接数据库

try{
        $db = new PDO('mysql:host=127.0.0.1;dbname=test;port=3306;charset=utf8','root','123456');
}catch(PDOException $e){
        echo 'mysql error: '.$e->getMessage();
}

1.excu()方式增删改,不推荐

$sql = "insert into test (username,password) values ('liming',123456)";
$res = $db->excu($sql);
echo $res //返回受影响的行数 1

2.PDOStatement类,增删改(推荐用这种方式,速度快,可以防止sql注入)
方式1-推荐

$sql = "insert into test (username,password) values (:name,:password)";
$data = [':name'=>'liming',':password'=>123456];
$stmt = $db->prepare($sql);
$res  = $stmt->execute($data);
echo $res //返回受影响的行数 1

方式2,增删改一样

$name='maoxiaoming';//要插入的数据一定要先用变量定义,不然会报错
$password= md5(123456);
$sql = $sql = "insert into test (username,password) values (:name,:password)";
$stmt = $db->prepare($sql);
$stmt->bindParam(':name',$name);
$stmt->bindParam(':password',$password);
$res = $stmt->execute();
echo $res //返回受影响的行数 1

3.PDOStatement类查询所有数据

$sql  = "select * from user";
$stmt = $db->prepare($sql);
$stmt->execute();
$res = $stmt->fetchAll(PDO::FATCH_ASSOC);

PHP之PDO的使用

//查询一条

$sql = "select * from user where id=:id";
$data = [':id'=>3];
$stmt = $db->prepare($sql);
$stmt->execute($data);
echo '<pre>';
print_r($stmt->fetch(PDO::FETCH_ASSOC));

猜你喜欢

转载自blog.51cto.com/woaijorden/2152508