Home  >  Article  >  Backend Development  >  PDO operates MYSQL (code example)

PDO operates MYSQL (code example)

藏色散人
藏色散人forward
2019-05-11 10:09:143071browse

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,&#39;root&#39;,&#39;123456&#39;);
    }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(&#39;id&#39;,$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(
        &#39;:id&#39;=>3,
        &#39;:sex&#39;=>&#39;0&#39;
    );
    $bool=$stmt->execute($data);
    //var_dump($bool);
    $result=$stmt->rowCount();
    var_dump($result);
    //修改操作
    $sql="UPDATE user_info SET zname=&#39;jack&#39; WHERE id=:id";
    $stmt=$pdo->prepare($sql);
    $id=5;
    $stmt->bindParam(&#39;:id&#39;,$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(
        &#39;:id&#39;=>2,
        &#39;:uid&#39;=>1,
        &#39;:zname&#39;=>&#39;john&#39;,
        &#39;:tel&#39;=>&#39;11111111111&#39;
    );
    $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!

Statement:
This article is reproduced at:aliyun.com. If there is any infringement, please contact admin@php.cn delete