//首先连接数据库
$dbms='mysql'; //数据库类型
$host='localhost'; //数据库主机名
$dbName='user'; //使用的数据库
$user='root'; //数据库连接用户名
$pass=''; //对应的密码
$dsn="$dbms:host=$host;dbname=$dbName";
$dbh = new PDO($dsn, $user, $pass); //初始化一个PDO对象
//增删改查都可以使用预处理方式
//增
$stmt = $pdo->prepare("INSERT `user` SET `name`= :name , `password`= md5(:password)");
$stmt -> execute(['name'=>'张三','password'=>'123123']);
echo '成功添加了:'.$stmt->rowCount().'条数据';
//删
$stmt = $pdo->prepare('DELETE FROM `user` WHERE `id` = :id');
if ($stmt->execute(['id'=>4])){
echo '成功删除:'.$stmt->rowCount().'条数据';
}else{
exit($stmt->errorInfo());
}
$stmt = null;
$pdo = null;
//改
$stmt = $pdo->prepare('UPDATE `user` SET `name`=:name,`password`= md5(:password) WHERE `id`=:id');
$stmt -> execute(['id'=>2,'name'=>'李四','password'=>'234234']);
echo '成功更新'.$stmt->rowCount().'条数据';
//查
$stmt = $pdo->prepare('SELECT `id`,`name` FROM `user` WHERE `id`>:id');
$stmt -> execute(['id'=>1]);
//将结果集绑定到变量上
$stmt->bindColumn('id',$id);
$stmt->bindColumn('name',$name);
$stmt->bindColumn('email',$email);
//循环输出结果
while($stmt->fetch(PDO::FETCH_BOUND)){
echo 'id:'.$id.' 姓名:'.$name.' 邮箱:'.$email ,'<br>';
}