mysql_fetch_array() 期望参数 1 是资源,给定的对象不起作用


mysql_fetch_array() expects parameter 1 to be resource, object given not working

每当我尝试运行此代码时,它都会显示错误。我是PHP,MySQL的新手。代码如下:

$id=mysqli_connect("localhost","root","") or die("Could not connect to MySQL server.");
$query="Select Code,Name from world.Country limit 10,5";
$query_results=mysqli_query($id,$query);
if($query_results==false)
{
echo"Failed";
}
while($row=mysql_fetch_array($query_results,MYSQL_BOTH))
{
    $Countrycode= $row['Code'];
    $Countryname= $row['Name'];
    print "$country_name($country_code)<br>'n";`//No display`
}
mysqli_close($id); 

Edit

有趣的是,即使您没有提供要选择的默认数据库,您的查询仍然有效,因为您在查询本身中提供了数据库标识符。所以我的第一个建议不是你遇到的实际问题。只有您正在使用mysql_fetch_array而不是mysqli_fetch_array看到该错误的事实。

以前的答案

您尚未选择要处理的任何数据库。您错过了呼叫

mysqli_select_db($id,$databaseName);

然后您将mysql_*函数与mysqli_* 混合。阅读 MySQLi 手册以获取正确的使用说明。您还可以在连接时提供数据库名称,如下所示

mysqli_connect("localhost","root","password","database") 

然后你必须使用 mysqli 获取结果,而不是mysql

mysqli_fetch_array

您错过了连接中的数据库名称:

$id=mysqli_connect("localhost","root","","DBNAME") or die("Could not connect to MySQL server.");

并将mysql_fetch_array更改为mysqli_fetch_array

while($row=mysqli_fetch_array($query_results)){
......
......
}
$id=mysqli_connect("localhost","root","",$databaseName) or die("Could not connect to MySQL server.");
$query="Select Code,Name from world.Country limit 10,5";
$query_results=mysqli_query($id,$query);
if($query_results==false) {
    echo"Failed";
}
while($row=mysqli_fetch_array($query_results,MYSQL_BOTH)){ // You used mysql_fetch_array
    $Countrycode= $row['Code'];
    $Countryname= $row['Name'];
    print "$country_name($country_code)<br>'n";`//No display`
}
mysqli_close($id); 

如果您使用的是MySQLI,那么您应该使用mysqli_fetch_array。