2011-06-03 54 views
0

我想知道我們是否需要使用select_db()功能,當我們查詢數據庫,因爲我們已經定義我們要編寫查詢像"select * from users"我們應該在php中使用select_db()嗎?

我想沒有它時所使用的表和它的工作,但我不知道知道功能提供了什麼樣的優點?

//$sau_db->select_db("users"); 

$query = "select * from users"; 

$results = $sau_db->query($query); 

echo "<ul>"; 
for($i=0;$i < $results->num_rows; $i++) 
{ 
    $row = $results->fetch_assoc(); 
    echo "<li>".$row["first_name"].' '.$row["last_name"]."</li>"; 
} 
echo "</ul>"; 
+0

你可以給代碼創建$ sau_db嗎?否則,我們無法確定您使用的數據庫抽象類型。 – SamT 2011-06-03 18:29:02

回答

4

選擇數據庫不同於選擇表格。一個數據庫可以包含多個表,而MySQL服務器可以包含多個數據庫。我不確定你使用什麼系統來訪問你的數據庫,但除非在別處配置(它很可能),通常有必要選擇一個數據庫。

通常按以下所示使用link

2

select_db不適用於表名,如果您沒有在您的連接中指定db實例,那麼select_db不適用於缺省數據庫來處理您的查詢。

2

使用select_db可消除您正在使用的數據庫的任何歧義。

通常,數據庫用戶與默認數據庫相關聯。當他們建立連接並進行任何查詢時,默認使用該數據庫來選擇/插入/更新/刪除/ etc。

通常,select_db()是明智的選擇,因爲如果默認數據庫發生更改,可能會產生災難性後果。例如,如果您有一個MYDBDEV,MYDBTEST和MYDBPROD數據庫,並且連接的用戶有一個默認的數據庫MYDBDEV,那麼如果由於某種原因某人將其更改爲具有MYDBPROD的默認數據庫,那麼您的代碼突然間正在修改MYDBPROD無需更改代碼或任何配置文件。

1

上面給出的非常正確的答案。

退房與默認的MySQL數據庫的一個例子你自己(在同一臺服務器上):

<?php 
// Make a MySQL Connection 
mysql_connect("localhost", "root", "") or die(mysql_error()); 
mysql_select_db("cdcol") or die(mysql_error()); 

// Retrieve all the data from the "example" table 
$result = mysql_query("SELECT * FROM cds") 
or die(mysql_error()); 

// store the record of the "example" table into $row 
$row = mysql_fetch_array($result); 
// Print out the contents of the entry 

echo "coloumn1: ".$row['titel']; 
echo " coloumn2: ".$row['interpret']; 

////////////////////// this will not work 
###################mysql_select_db("mysql") or die(mysql_error()); 
// Retrieve all the data from the "example" table 
$result = mysql_query("SELECT * FROM help_category") 
or die(mysql_error()); 

// store the record of the "example" table into $row 
$row = mysql_fetch_array($result); 
// Print out the contents of the entry 

echo "<br><br>coloumn1: ".$row['help_category_id']; 
echo " coloumn2: ".$row['name']; 
?> 

只有當你取消註釋mysql_select_db(「MySQL的」),才第二次查詢將工作, 否則你得到如下的錯誤,因爲當前的連接是指cdcol數據庫:

表「cdcol.help_category」不存在