以pikachu数据库为例,数据库名: pikachu
1.连接数据库
<?php
$dsn = 'mysql:host=localhost; port=3306; dbname=pikachu'; // 这里的空格比较敏感
$username = 'root';
$password = 'root';
try {
$pdo = new PDO($dsn, $username, $password);
var_dump($pdo);
}catch(PDOException $e){
// echo $e->getMessage();
die('Connection error:'. $e->getMessage());
}
?>
连接成功。
2. pdo查询
<?php
$dsn = 'mysql:host=127.0.0.1; dbname=pikachu';
$username = 'root';
$pwd = 'root';
$pdo = new PDO($dsn, $username,$pwd); // 连接数据库
$sql = 'select * from users where id=:id';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':id',1);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<pre>';
print_r($rows);
$pdo = null;
?>
:id 占位符
3.pdo更新
<?php
$dsn = 'mysql:host=127.0.0.1; dbname=pikachu';
$username = 'root';
$pwd = 'root';
$pdo = new PDO($dsn, $username,$pwd);
$sql = 'update users set level="4" where id=:id';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':id',1);
stmt->execute();
$pdo = null;
?>
4.pdo插入
<?php
$dsn = 'mysql:host=127.0.0.1; dbname=pikachu';
$username = 'root';
$pwd = 'root';
$pdo = new PDO($dsn, $username,$pwd);
$sql = 'insert into users(`id`,`username`,`password`,`level`) values(:id,:username,:password,:level)';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':id',4);
$stmt->bindValue(':username','Bob');
$stmt->bindValue(':password','e99a18c428cb38d5f260853678922e04');
$stmt->bindValue(':level','5');
$stmt->execute();
$id = $pdo->lastInsertId();
echo '<pre>';
var_dump($id);
$pdo = null;
?>
5. pdo删除
<?php
$dsn = 'mysql:host=127.0.0.1; dbname=pikachu';
$username = 'root';
$pwd = 'root';
$pdo = new PDO($dsn, $username,$pwd);
$sql = 'delete from pikachu where id = :id';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':id',1);
$stmt->execute();
// 返回受影响的行数,删除了多少行。
$rowCount = $stmt->rowCount();
echo '<pre>';
var_dump($rowCount);
$pdo = null;
?>