Home > php教程 > php手册 > PHP与Mysql连接

PHP与Mysql连接

WBOY
Release: 2016-06-13 10:55:49
Original
790 people have browsed it

登陆后就像是这样:

 
 

 

 

首先我们来创建一个用于测试的数据库。

偷懒的话直接在phpMyAdmin中创建就可以了。

我创建了一个books数据库,里面有一个item的表:

 


接下来实现一个功能:连接数据库并打印出表中的内容。

连接数据库


[php]
$db_host='localhost'; 
$db_user='root'; 
$db_pass='1'; 
$db_name='books'; 
$conn=mysql_connect($db_host,$db_user,$db_pass) 
mysql_select_db($db_name,$conn); 
mysql_query("set names 'utf8'"); 
 
if(!$conn) echo "failed!";  
else echo "success!"; 
?> 

$db_host='localhost';
$db_user='root';
$db_pass='1';
$db_name='books';
$conn=mysql_connect($db_host,$db_user,$db_pass)
mysql_select_db($db_name,$conn);
mysql_query("set names 'utf8'");

if(!$conn) echo "failed!";
else echo "success!";
?>

如果连接正常,浏览器就会显示seccess!

 


创建list.php


[php]
        include("conn.php"); 
        $sql="select * from items"; 
        $query=mysql_query($sql); 
echo "

"; 
while($row = mysql_fetch_array($query)) 

        $id=$row["id"]; 
        $name=$row["name"]; 
 echo ""; 

echo "
Id Name
".$id." ".$name."
"; 
mysql_close(); 
?> 

        include("conn.php");
        $sql="select * from items";
        $query=mysql_query($sql);
echo "

";
while($row = mysql_fetch_array($query))
{
        $id=$row["id"];
        $name=$row["name"];
 echo "";
}
echo "
Id Name
".$id." ".$name."
";
mysql_close();
?>

 
 

 

 

打完收工。

 

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