background image

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

本节学习下

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

开数据库等。

1,打开一个连接,并选择数据库
<html>
<head>
<title>打开连接并选择数据库-www.jbxue.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>";
?>