<?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