【问题标题】:Warning: mysqli_query() expects parameter 1 to be mysqli, resource given [duplicate]警告:mysqli_query() 期望参数 1 为 mysqli,给定资源 [重复]
【发布时间】:2012-04-26 23:43:14
【问题描述】:

我的代码中有这个错误,我不知道如何解决我的代码:

<?php
session_start();
include_once"connect_to_mysql.php";

$db_host = "localhost";
// Place the username for the MySQL database here
$db_username = "root"; 
// Place the password for the MySQL database here
$db_pass = "****"; 
// Place the name for the MySQL database here
$db_name = "mrmagicadam";

// Run the actual connection here 
$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");        
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysql_error());
$menuDisplay="";


while($row=mysql_fetch_array($query)) {
    $pid=$row["id"];
    $linklabel=$row["linklabel"];
$menuDisplay='<a href="index.php?pid=' .$pid . '">' .$linklabel. '</a><br/>';
}
mysqli_free_result($query);

?>

这是错误:

警告:mysqli_query() 期望参数 1 为 mysqli,第 17 行 C:\xampp\htdocs\limitless\connect_to_mysql.php 中给出的资源

我做错了什么?

【问题讨论】:

  • 提示:使用搜索功能搜索您收到的确切错误消息。我可以向你保证,这个问题之前已经回答过很多次了。

标签: php mysql


【解决方案1】:

您正在混合使用 mysqlimysql 扩展名,这将不起作用。

你需要使用

$myConnection= mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql"); 

mysqli_select_db($myConnection, "mrmagicadam") or die ("no database");   

mysqli比原来的mysql扩展有很多改进,所以建议你使用mysqli

【讨论】:

  • 或者跳转到 PDO,它提供了 MySQLi 没有的许多功能,并且可以更轻松地避免 SQL 注入。此外,它还可以让您进行对象映射(如果您不想使用 ORM 但喜欢这个想法)...stackoverflow.com/questions/13569/…
【解决方案2】:

您使用了不正确的语法。如果您阅读文档mysqli_query(),您会发现它需要两个参数。

混合 mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

mysql $link一般表示,建立mysqli连接的资源对象查询数据库。

所以有两种方法可以解决这个问题

mysqli_query();

$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql"); 
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));

或者,使用mysql_query()(现在已过时)

$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");        
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());

正如 cmets 中所指出的,请注意使用 die 来获取错误。它可能会在不经意间为查看者提供一些敏感信息。

【讨论】:

  • 在您的第二个示例中,您将混合 MySQL 和 MySQLi 库。我听说这在某些情况下有效,但我认为只坚持一个是明智的?
  • 在代码中使用die(mysqli_error($conn)); 是一个非常糟糕的主意,因为它可能会泄露敏感信息。更多解释见这篇文章:mysqli or die, does it have to die?
猜你喜欢
  • 2013-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-29
  • 1970-01-01
相关资源
最近更新 更多