您好,登錄后才能下訂單哦!
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));
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。