2011-06-03 53 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”不存在