PHP之PDO的使用
阿新 • • 發佈:2018-07-31
sql註入 log 行數 ins int images bin catch -o 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);
//查詢一條
$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));
PHP之PDO的使用