Mysqli_Query警告:mysqli_query()期望参数1为mysqli

sha*_*maa 8 php mysql

我的代码中出现此错误,我不知道如何解决我的代码:

<?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);

?>
Run Code Online (Sandbox Code Playgroud)

这是错误的:

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

我做错了什么?

F21*_*F21 26

你正在混合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");   
Run Code Online (Sandbox Code Playgroud)

mysqli与原始mysql扩展相比有许多改进,因此建议您使用mysqli.

  • 或者跳转到PDO,它提供了MySQLi没有的许多功能,并且使得避免SQL注入变得容易得多.另外,它允许您进行对象映射(如果您不想使用ORM但是喜欢这个想法)... http://stackoverflow.com/questions/13569/mysqli-or-pdo-what-are-the -pros和禁忌症 (3认同)

Sta*_*arx 7

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

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

mysql $link 通常意味着,已建立的mysqli连接的资源对象用于查询数据库.

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

使用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());
Run Code Online (Sandbox Code Playgroud)

或者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));
Run Code Online (Sandbox Code Playgroud)