The example in this article describes how php+mysqli uses an object-oriented approach to query the database. Share it with everyone for your reference. The specific implementation method is as follows:
<?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(); ?>
I hope this article will be helpful to everyone’s PHP programming design.