使用mysqli_connect和mysql_select_db

时间:2013-09-28 09:10:20

标签: php mysql database

此代码可以正常使用!

$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中删除database_name时我会使用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);

3 个答案:

答案 0 :(得分:4)

替换您的代码:

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

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

答案 1 :(得分:2)

请不要混用mysqlimysql,因为它们是不同的模块。

在您使用mysql_select_dbmysql_error的第二个代码块中,第一个需要mysql连接,而不是mysqli连接。

答案 2 :(得分:-1)

参数的顺序已更改为:

mysql_select_db($Database, $Connection);

收件人:

mysqli_select_db($Connection, $Database);