php中pdo例子

下面是從其餘博客看到的代碼php

<?php
$dbh = new PDO('mysql:host=localhost;dbname=access_control', 'root', '');  
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
$dbh->exec('set names utf8'); 
/*添加*/
//$sql = "INSERT INTO `user` SET `login`=:login AND `password`=:password"; 
$sql = "INSERT INTO `user` (`login` ,`password`)VALUES (:login, :password)";  $stmt = $dbh->prepare($sql);  $stmt->execute(array(':login'=>'kevin2',':password'=>''));  
echo $dbh->lastinsertid();  
/*修改*/
$sql = "UPDATE `user` SET `password`=:password WHERE `user_id`=:userId";  
$stmt = $dbh->prepare($sql);  
$stmt->execute(array(':userId'=>'7', ':password'=>'4607e782c4d86fd5364d7e4508bb10d9'));  
echo $stmt->rowCount(); 
/*刪除*/
$sql = "DELETE FROM `user` WHERE `login` LIKE 'kevin_'"; //kevin%  
$stmt = $dbh->prepare($sql);  
$stmt->execute();  
echo $stmt->rowCount();  
/*查詢*/
$login = 'kevin%';  
$sql = "SELECT * FROM `user` WHERE `login` LIKE :login";  
$stmt = $dbh->prepare($sql);  
$stmt->execute(array(':login'=>$login));  
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){     
 print_r($row);  
}  
print_r( $stmt->fetchAll(PDO::FETCH_ASSOC)); 
?>

 

注意事項:mysql

1,連接pdo時,host和database後面不能加空格,這三大項是用逗號隔開的.sql

$dbh = new PDO('mysql:host=localhost;dbname=access_control', 'root', ''); fetch

 

2,若是不慎把這三項在一個雙引號裏面,php會報下面這個錯誤.spa

PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[28000] [1045] Access denied for user 'komiles'@'localhost' (using password: NO)'code

相關文章
相關標籤/搜索