Home > php教程 > php手册 > php+mysqli使用面向对象方式查询数据库实例,mysqli面向对象

php+mysqli使用面向对象方式查询数据库实例,mysqli面向对象

WBOY
Release: 2016-06-13 09:16:11
Original
964 people have browsed it

php+mysqli使用面向对象方式查询数据库实例,mysqli面向对象

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

<&#63;php
//第一步:创建数据连接对象
$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 = "select title,contents from news limit 5,5";
//第三步:执行,显示结果
$res = $mysqli->query($sql) or die($mysqli->error);
// 返回值 $res 为资源类型(获取到结果的资源类型)
if($res){
 while($row = $res->fetch_assoc()){
//注意:fetch_assoc()为 MySQLi_Result 里的函数,详情见手册
 echo "标题:".$row['title']."<br>内容:".$row['contents']."<hr>";
 }
}
//第四步,释放结果集,关闭连接
$res->free();
$mysqli->close();
&#63;>

Copy after login

希望本文所述对大家的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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template