mysqli_select_db()函數(shù)用于更改連接的默認(rèn)數(shù)據(jù)庫(kù)。
mysqli_select_db()函數(shù)接受表示現(xiàn)有數(shù)據(jù)庫(kù)的字符串值,并將其作為默認(rèn)數(shù)據(jù)庫(kù)。
mysqli_select_db($con, name)
序號(hào) | 參數(shù)及說(shuō)明 |
---|---|
1 | con(必需) 這是一個(gè)表示與MySQL Server的連接的對(duì)象。 |
2 | name(必需) 這是一個(gè)字符串值,表示數(shù)據(jù)庫(kù)名稱。 |
PHP mysqli_select_db()函數(shù)返回一個(gè)布爾值,如果操作成功,則為true,否則為false。
此函數(shù)最初是在PHP版本5中引入的,并且可以在所有更高版本中使用。
以下示例演示了mysqli_select_db()函數(shù)的用法(面向過(guò)程風(fēng)格)-
<?php //建立連接 $con = mysqli_connect("localhost", "root", "password", "mydb"); //選擇數(shù)據(jù)庫(kù) mysqli_query($con, "CREATE DATABASE NewDatabase"); mysqli_select_db($con, "NewDatabase"); //檢索當(dāng)前數(shù)據(jù)庫(kù)名稱 $res = mysqli_query($con, "SELECT DATABASE()"); while ($row = mysqli_fetch_row($res)) { print("當(dāng)前數(shù)據(jù)庫(kù): ".$row[0]); } //關(guān)閉連接 mysqli_close($con); ?>
輸出結(jié)果
當(dāng)前數(shù)據(jù)庫(kù): newdatabase
在面向?qū)ο箫L(fēng)格中,此函數(shù)的語(yǔ)法為$con->select_db();。以下是面向?qū)ο箫L(fēng)格中此函數(shù)的示例;
<?php //建立連接 $con = new mysqli("localhost", "root", "password", "mydb"); //檢索當(dāng)前數(shù)據(jù)庫(kù)名稱 $res = $con->query("SELECT DATABASE()"); while ($row = $res->fetch_row()) { print("初始數(shù)據(jù)庫(kù): ".$row[0]."\n"); } //選擇數(shù)據(jù)庫(kù) $con->query("CREATE DATABASE NewDatabase"); $con->select_db("NewDatabase"); //檢索當(dāng)前數(shù)據(jù)庫(kù)名稱 $res = $con->query("SELECT DATABASE()"); while ($row = $res->fetch_row()) { print("當(dāng)前數(shù)據(jù)庫(kù): ".$row[0]); } //關(guān)閉連接 $res = $con -> close(); ?>
輸出結(jié)果
初始數(shù)據(jù)庫(kù): mydb 當(dāng)前數(shù)據(jù)庫(kù): newdatabase
除了在連接時(shí)指定數(shù)據(jù)庫(kù),您還可以稍后使用此函數(shù)更改連接的默認(rèn)數(shù)據(jù)庫(kù),如下所示:
<?php //建立連接 $con = mysqli_connect("localhost", "root", "password"); //選擇數(shù)據(jù)庫(kù) mysqli_select_db($con, "mydb"); print("選擇數(shù)據(jù)庫(kù) ..."."\n"); mysqli_query($con, "CREATE TABLE IF NOT EXISTS my_team(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))"); print("創(chuàng)建表 ..."."\n"); //將記錄插入到my_team表中 mysqli_query($con, "insert into my_team values(1, 'Shikhar', 'Dhawan', 'Delhi', 'India')"); mysqli_query($con, "insert into my_team values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')"); mysqli_query($con, "insert into my_team values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')"); mysqli_query($con, "insert into my_team values(4, 'Virat', 'Kohli', 'Delhi', 'India')"); print("插入記錄 ..."."\n"); //關(guān)閉連接 mysqli_close($con); ?>
輸出結(jié)果
選擇數(shù)據(jù)庫(kù) ... 創(chuàng)建表 ... 插入記錄 ...
更改連接的默認(rèn)數(shù)據(jù)庫(kù):
<?php $connection_mysql = mysqli_connect("localhost", "root", "password","mydb"); if (mysqli_connect_errno($connection_mysql)){ echo "連接MySQL失敗: " . mysqli_connect_error(); } $res = mysqli_select_db($connection_mysql,"testdb"); if($res){ echo "選擇的數(shù)據(jù)庫(kù)"; }else{ echo "發(fā)生錯(cuò)誤"; } mysqli_close($connection_mysql); ?>
輸出結(jié)果
選擇的數(shù)據(jù)庫(kù)