php 打开连接并选择数据库的实例代码

发布时间:2019-12-31编辑:脚本学堂
本文介绍下,用php创建数据库连接,并选择具体数据库的实现代码,有需要的朋友,可以参考学习下。

本节学习下php连接数据库的方法,通过几个例子,来学习如何创建数据库连接,如何打开数据库等。

1,打开一个连接,并选择数据库

<html>
<head>
<title>打开连接并选择数据库-www.jb200.com</title>
</head>
<body>
<?php
$user = "root";
$pass = "123456";
$db = "test_news";
$link =  mysql_connect( "192.168.0.10", $user, $pass );

if ( ! $link ){
     die( "Couldn't connect to MySQL" );
}
print "Successfully connected to server<P>";
mysql_select_db( $db ) or die ( "Couldn't open $db: ".mysql_error() );
print "Successfully selected database "$db"<P>";
mysql_close( $link );
?>
</body>
</html>

2,连接mysql数据库

<?
$connection = @mysql_connect("192.168.0.10", "test_news", "password") or die(mysql_error());

$dbs = @mysql_list_dbs($connection)or die(mysql_error());
$db_list ="<ul>";
$i =0;

while ($i < mysql_num_rows($dbs)){
     $db_names[$i] = mysql_tablename($dbs,$i);
     $db_list .= "<li>$db_names[$i]";
     $i++;
}
$db_list .="</ul>";
?>

<HTML>
<HEAD>
<TITLE>MySQL Databases</TITLE>
</HEAD>
<BODY>
<P><strong>Databases on localhost</strong>:</P>
<? echo "$db_list"; ?>
</BODY>
</HTML>

3,列出数据库变量信息

<html>
<head>
<title>输出一些mysql数据库信息-www.jb200.com</title>
</head>
<body>
<?php
$user = "root";
$pass = "123456";
$link =  mysql_connect( "192.168.0.10", $user, $pass );
if ( ! $link )
    die( "Couldn't connect to MySQL" );

$db_res = mysql_list_dbs( $link );
$num = mysql_num_rows( $db_res );

for( $x = 0; $x < $num; $x++ )
    print mysql_tablename( $db_res, $x )."<br>";

mysql_close( $link );
 ?>
</body>
</html>

4,用变更储存mysql连接信息

<?php
//
$hostname="192.168.0.10";
$username="root";
$password="123456";
$dbname="test_news";
$usertable="Employee";
$yourfield = "FirstName";

mysql_connect($hostname,$username, $password) OR DIE ("Unable to connect to database! Please try again later.");
mysql_select_db($dbname);

$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if($result) {
    while($row = mysql_fetch_array($result)){
        $name = $row["$yourfield"];
        echo "Name: ".$name;
    }
}
?>