PHP连接并输出数据库数据实例代码

Author: 陌小雨Date: 2017-10-21View: 55

整理下日前学习php连接数据库并输出数据的代码:

php7版本:

<?php
@header('Content-type: text/html;charset=UTF-8');
$mysqli=new mysqli("localhost","root","","tb");
mysqli_query($mysqli,'SET NAMES utf8');
 /* check connection */
    if ( mysqli_connect_errno ()) {
         printf ( "Connect failed: %s\n" ,  mysqli_connect_error ());
        exit();
    }
    $limit = 50;
	$list='';
    $query  =  "SELECT * FROM items LIMIT ".$limit ;
    $result  =  $mysqli -> query ( $query );
    while($row  = $result -> fetch_array ( MYSQLI_ASSOC )){
$name = $row["itemtitle"]; //将数据从数组取出
$price = $row["itemprice"];
$url = $row["itemurl"];
$img = $row["itemimg"];
$list .='<article class="excerpt excerpt-c5"><a class="thumbnail" href="'.$url.'" target="_blank"><img src="'.$img.'" class="thumb" style="display: inline;"><div class="zdy">'.$price.'</div></a><h2>'.$name.'</h2></article>'; 
}
 /* free result set */
    $result -> free ();
 
    /* close connection */
    $mysqli -> close ();
?>

php5版本

<?php
$link=mysql_connect("localhost","","");
MySQL_query("SET NAMES 'gbk'");
$my_db = mysql_select_db(test,$link);
$sql = "select * from books";
$result = mysql_query($sql, $link); // 执行查询语句
while ($bookInfo = mysql_fetch_array($result)){ //返回查询结果到数组
$name = $bookInfo["name"]; //将数据从数组取出
$price = $bookInfo["price"];
$isbn = $bookInfo["ISBN"];
echo "<li>《".$name."》</br>价格:".$price."</br>ISBN:".$isbn."</li>";  //输出数据
}
mysql_free_result($result);
mysql_close($link);
?>