Home >Backend Development >PHP Tutorial >Basic operations of reading data in Php
This article mainly shares with you the basic operation examples of reading data in Php. We will first analyze the steps with you. Then share the code with everyone, hoping to help everyone.
Basic steps for PHP database operation:
Step 1: Link to mysql database server $link = mysql_connect(host, username, password);
Step 2 : Select the database to be operated mysql_select_db (database name)
Step 3: Set character set
Step 4: Execute sql statement
Step 5: Get data
The following are examples of operation steps:
<?php //数据库的配置信息 $db_host = "localhost"; $db_user = "root"; $db_pwd = "root"; $db_name = "数据库名字"; //前缀 $db_prefix = "007_"; //链接数据库 $link = @mysql_connect($db_host,$db_user,$db_pwd); if(!$link){ echo "连接mySq数据库失败"; } //选择当前的数据库 if(!mysql_select_db($db_name,$link)){ echo "打开数据库失败"; } //设置字符集 mysql_query("set names utf8"); //查询语句 $sql = "select id,title,author,source,hits,addate from {$db_prefix}news order by id desc"; //拿到资源集合 $result = mysql_query($sql); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> <style type="text/css"> td,th{ padding: 5px;color:#444;font-size: 14px;border: 1px solid #ccc; } </style> </head> <body> <table width="1000" border = "1" style="border-collapse: collapse;"> <tr> <th>编号</th> <th>标题</th> <th>作者</th> <th>来源</th> <th>点击量</th> <th>发布时间</th> </tr> <?php while($row = mysql_fetch_row($result)){ //循环取数据 ?> <tr> <th><?php echo $row[0]?></th> <th><?php echo $row[1]?></th> <th><?php echo $row[2]?></th> <th><?php echo $row[3]?></th> <th><?php echo $row[4]?></th> <th><?php echo $row[5]?></th> </tr> <?php }?> </table> </body> </html>
Related recommendations:
Several methods of reading database information in php_PHP tutorial
The above is the detailed content of Basic operations of reading data in Php. For more information, please follow other related articles on the PHP Chinese website!