Blogger Information
Blog 34
fans 0
comment 0
visits 39162
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
mysql数据库 pdo操作——线上培训五期——2019-03-21
黄健的博客
Original
668 people have browsed it
<?php
/**
 * Created by PhpStorm.
 * User: hello word!
 * Date: 2019/3/24
 * Time: 9:39
 */
function con(){
    $type = 'mysql';
    $host = '127.0.0.1'; //linux unix macos 用 localhost
    $dbname = 'gift';
    $charset = 'utf8';
    $dns = $type.':host='.$host.';dbname='.$dbname.';charset='.$charset;
    try{
        $pdo = new PDO($dns,'root','root');
        //关闭:并非必须,因为脚本结束后会自动关闭,但是推荐显示关闭它
    }catch (PDOException $e){
        echo $e->getMessage();
    }
    return $pdo;
}
function add($table='',$field='',$val='',$flag=false){
    $pdo=con();
    //新增需要参数 1 表名 ,2 字段名, 3 对应值 4 是否添加字段(主键自增时可以)
    //拼装sql
    if($flag==false){
        $sql='INSERT INTO '.$table.' ( '.$field.' ) VALUES'.'( '.$val.' )';
    }else{
        $sql='INSERT INTO '.$table.'VALUES'.'( '.$val.' )';
    }
    // INSERT INTO user ( uname, sex ) VALUES( '绿谷出久1' , '男' )
    $stmt=$pdo->prepare($sql);
    if($stmt->execute()){
        echo ($stmt->rowCount()>0) ? '成功添加了'.$stmt->rowCount().'条数据' : '添加失败';
    }else{
        exit(print_r($stmt->errorInfo(),true));
    }
//    echo $sql;
}
add('user',' uname, sex '," '绿谷出久1' , '男' ");
//修改
function upd($table='',$set='',$where=''){
    $pdo=con();
    $sql='UPDATE `'.$table.'` SET '.$set. ' where '.$where;
    // UPDATE `user` SET `uname` = '爆豪胜己' where uid = 13
    $stmt=$pdo->prepare($sql);
    if($stmt->execute()){
        echo ($stmt->rowCount()>0) ? '成功修改了'.$stmt->rowCount().'条数据' : '修改失败';
    }else{
        exit(print_r($stmt->errorInfo(),true));
    }
}
//upd('user'," `uname` = '爆豪胜己' ",'uid = 13 ');
//删除
function del($table='',$where=''){
    $pdo=con();
    $sql='DELETE FROM `'.$table.'` where '.$where;
    // DELETE FROM `user` where uid = 1
    $stmt=$pdo->prepare($sql);
    if($stmt->execute()){
        echo ($stmt->rowCount()>0) ? '成功刪除了'.$stmt->rowCount().'条数据' : '刪除失败';
    }else{
        exit(print_r($stmt->errorInfo(),true));
    }
}
//del('user','uid = 1');

对应sql

INSERT INTO user ( uname, sex ) VALUES( '绿谷出久1' , '男' )

UPDATE `user` SET `uname` = '爆豪胜己' where uid = 13


DELETE FROM `user` where uid = 1

Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post