php+mysqli使用面向对象方式更新数据库实例_PHP

WBOY
Release: 2016-05-31 13:17:43
Original
875 people have browsed it

本文实例讲述了php+mysqli使用面向对象方式更新数据库的方法,分享给大家供大家参考。具体实现方法如下:

代码如下:

//第一步:创建数据连接对象
$mysqli = new MySQLi("localhost","root","123456");//默认的 MySQL的类,其属性与方法见手册
if($mysqli->connect_error){//connect_error为属性,报错
 die("数据库连接失败:".$mysqli->connect_errno."--".$mysqli->connect_error);// connect_errno:错误编号
}
$mysqli->select_db("liuyan");//选择数据库
$mysqli->query("set names 'GBK'");

//第二步:更新其中一条信息,代码如下
$sql = "update news set title='游泳世界杯叶诗文夺冠' where id=17";
//第三步:执行
$res = $mysqli->query($sql);//与select的返回值不同,update的返回值为true(如果成功),失败则返回false
//判断执行是否成功
if(!$res){
 echo "更新数据失败";
}else{
 if($mysqli->affected_rows>0){//$mysql->affected_rows:返回前一个操作影响的数据库行数
  echo "更新数据成功";
 }else{
  echo "执行成功,但没有数据更新";//比如当你第二次执行这段代码时,就没有数据更新
 }
}
//关闭数据库连接,与 select 不同,这里不用释放查询结果集
$mysqli->close();
?>

希望本文所述对大家的php程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!