Home > Article > Backend Development > PDO operates MYSQL (code example)
This article will introduce you to the method of operating MYSQL with PDO. I hope it will be helpful to friends in need!
<?php //PDO操作mysql数据库 增删改查 //1.准备dsn $mysql_dsn="mysql:host=localhost;dbname=cz;charset=utf8"; //2.连接数据库 try{ $pdo=new PDO($mysql_dsn,'root','123456'); }catch(PDOException $e){ echo $e->getMessage(); } //3.设置错误模式 $pdo->setAttribute(3,1); //查询操作 $sql="SELECT * FROM user_info WHERE id=:id"; $stmt=$pdo->prepare($sql); // //绑定参数 $id=1; $stmt->bindParam('id',$id); $bool=$stmt->execute(); if(!$bool){ //报错 var_dump("SQL执行错误"); exit; }else{ $result=$stmt->fetch(2); var_dump($result); } //删除操作 $sql="DELETE FROM user_info WHERE id=:id and sex=:sex"; $stmt=$pdo->prepare($sql); $data=array( ':id'=>3, ':sex'=>'0' ); $bool=$stmt->execute($data); //var_dump($bool); $result=$stmt->rowCount(); var_dump($result); //修改操作 $sql="UPDATE user_info SET zname='jack' WHERE id=:id"; $stmt=$pdo->prepare($sql); $id=5; $stmt->bindParam(':id',$id); $bool=$stmt->execute(); var_dump($bool); $nums=$stmt->rowCount(); var_dump($nums); //添加操作 $sql="INSERT INTO user_info(id,uid,zname,tel) VALUES(:id,:uid,:zname,:tel)"; $stmt=$pdo->prepare($sql); $data=array( ':id'=>2, ':uid'=>1, ':zname'=>'john', ':tel'=>'11111111111' ); $bool=$stmt->execute($data); $nums=$stmt->rowCount(); var_dump($nums); ?>
Attention! The above database operations can prevent SQL injection problems.
The above is the detailed content of PDO operates MYSQL (code example). For more information, please follow other related articles on the PHP Chinese website!