Blogger Information
Blog 19
fans 0
comment 0
visits 13272
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP增删改PDO作业-2019年3月21
倪偌卟離
Original
541 people have browsed it

<?php

//作业:PDO增删改

//创建PDO类连接数据库

function con(){

$dsn='mysql:host=127.0.0.1;dbname=xuexi;charset=utf8;port=3306';

$dbname='root';

$dbpw='root';

$pdo=new PDO($dsn,$dbname,$dbpw);

try{

$pdo=new PDO($dsn,$dbname,$dbpw);

}catch(PDOException $e){

print_r($e->getMessage());

}

  return $pdo;

}

//数据库修改数据的方法

function modify($table,$field,$where){

//连接数据库

$c=con();

//组合数据库修改语言

//$modify='UPDATE `user` SET `name` = "王正义" WHERE `id`=9';

$modify=' UPDATE ';

$modify.=$table;

$modify.=' SET ';

$modify.=$field;

$modify.=' WHERE ';

$modify.=$where;

//加入预执行方法

$a=$c->prepare($modify);

//开始执行

$a->execute();

//判断执行结果是否为空,不为空则输出成功,为空则输出失败

if ($a->rowCount() > 0) {

    echo '成功更新了' . $a->rowCount() . '条记录';

} else {

    echo '没有记录被更新';

  }

}

modify('`user`','`name` = "张正义"','`age`>40');

//数据库添加数据的方法

function insert($table,$field,$value){

//连接数据库

$c=con();

//开始组装SQL添加数据语句

$ins=' INSERT INTO ';

$ins.=$table;

$ins.=$field;

$ins.=' VALUES ';

$ins.=$value;

//$ins=' INSERT INTO `user` (`name`,`age`,`phone`) VALUES ("钱三爷","50","12345678901") ';

$b=$c->prepare($ins);

$b->execute();

if($b->rowCount()>0){

echo '成功添加了'.$b->rowCount().'条记录';

}else{

echo '添加失败';

}

}

insert('`user`','(`name`,`age`,`phone`)','("付五","50","12345678901")');

//数据库删除数据的方法

function delete($table,$where){

$c=con();

//开始组装数据库语句

$del='DELETE FROM ';

$del.=$table;

$del.=' WHERE ';

//$del.=$field;

$del.=$where;

//$del='DELETE FROM `user` WHERE `name`="张正义"';

$d=$c->prepare($del);

$d->execute();

if($d->rowCount()>0){

echo '成功删除了'.$d->rowCount().'条记录';

}else{

echo '删除失败';

}

}

delete('`user`','`name`="王二"');

?>


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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!