在PHP中使用mysql_fetch_assoc时出现警告

时间:2008-10-04 01:43:43

标签: php mysql

  

可能重复:
  Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result

当我运行我的php页面时,我收到此错误并且不知道什么是错的,有人可以帮忙吗?如果有人需要更多信息,我会发布整个代码。

Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in
H:\Program Files\EasyPHP 2.0b1\www\test\info.php on line 16
<?PHP

    $user_name = "root";
    $password = "";
    $database = "addressbook";
    $server = "127.0.0.1";

$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);

if ($db_found) {

    $SQL = "SELECT * FROM tb_address_book";
    $result = mysql_query($SQL);

    while ($db_field = mysql_fetch_assoc($result)) {
        print $db_field['ID'] . "<BR>";
        print $db_field['First_Name'] . "<BR>";
        print $db_field['Surname'] . "<BR>";
        print $db_field['Address'] . "<BR>";
    }    

    mysql_close($db_handle);

}
else {
    print "Database NOT Found ";
    mysql_close($db_handle);
}

?>

2 个答案:

答案 0 :(得分:11)

这通常意味着您的SQL中出现了错误。

$sql = "SELECT * FROM myTable"; // table name only do not add tb
$result = mysql_query($sql);
var_dump($result);    // bool(false)

显然,false不是MySQL资源,因此您会收到该错误。

使用现在粘贴的代码进行编辑

while循环之前的行上,添加以下内容:

if (!$result) {
    echo "Error. " . mysql_error();
} else {
    while ( ... ) {
       ...
    }
}

确保tb_address_book表确实存在并且您已正确连接到数据库。

答案 1 :(得分:0)

<?PHP

    $user_name = "root";
    $password = "";
    $database = "addressbook";
    $server = "127.0.0.1";

$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);

if ($db_found) {

    $SQL = "SELECT * FROM tb_address_book";
    $result = mysql_query($SQL);

    while ($db_field = mysql_fetch_assoc($result)) {
        print $db_field['ID'] . "<BR>";
        print $db_field['First_Name'] . "<BR>";
        print $db_field['Surname'] . "<BR>";
        print $db_field['Address'] . "<BR>";
    }    

    mysql_close($db_handle);

}
else {
    print "Database NOT Found ";
    mysql_close($db_handle);
}

?>