PDO Mode Connection Database
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 () mode additions and deletions, not recommended
$sql = "insert into test (username,password) values (‘liming‘,123456)";$res = $db->excu($sql);echo $res //返回受影响的行数 1
2.PDOStatement class, add and delete changes (recommended in this way, fast, can prevent SQL injection)
Mode 1-Recommended
$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
Mode 2, adding and deleting the same
$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 class query all data
$sql = "select * from user";$stmt = $db->prepare($sql);$stmt->execute();$res = $stmt->fetchAll(PDO::FATCH_ASSOC);
Query A
$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));
Use of the PHP PDO