2013-09-28 60 views
-4

此代碼正常工作!使用mysqli_connect和mysql_select_db

$con=mysqli_connect("localhost","root","","laboratory"); 
// Check connection 
if (mysqli_connect_errno()) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

$result = mysqli_query($con,"SELECT * FROM test"); 

while($row = mysqli_fetch_array($result)) 
    { 
    echo $row['name']; 
    echo "<br>"; 
    } 

mysqli_close($con); 

但是當我刪除數據庫名稱從mysqli_connect我會用通過mysql_select_db,出現以下錯誤:「警告:mysql_select_db()預計參數2是資源,目標在給定的」改變後

代碼:

$con=mysqli_connect("localhost","root",""); 
// Check connection 
if (mysqli_connect_errno()) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

$db_selected = mysql_select_db("laboratory", $con); 

if (!$db_selected) 
    { 
    die ("Can\'t use laboratory : " . mysql_error()); 
    } 

$result = mysqli_query($con,"SELECT * FROM test"); 

while($row = mysqli_fetch_array($result)) 
    { 
    echo $row['name']; 
    echo "<br>"; 
    } 

mysqli_close($con); 
+2

不能調用MYSQL *功能。它不是必需的,因爲有'mysqli_select_db' – hek2mgl

回答

2

請不要混合mysqlimysql,因爲它們是不同的模塊。

在您的第二個代碼塊中,您使用的是mysql_select_dbmysql_error,第一個需要連接mysql,而不是mysqli連接。

+0

我的問題沒有解決。 – Daniyal

+1

@Daniyal是否更改了$ db_selected = mysql_select_db(「laboratory」,$ con);使用mysqli等效替代? – OIS

4

更換你的代碼:* mysqli的資源

$db_selected = mysqli_select_db("laboratory", $con);,而不是

$db_selected = mysql_select_db("laboratory", $con);