错误警告:php中的mysql_fetch_assoc()

Hai*_* IT -2 php

可能重复:
警告:mysql_fetch_array():提供的参数不是有效的MySQL结果

在db.php我有:

<?php
class connect {

    private $host = "localhost";
    private $user = "root";
    private $pass = "";
    private $database = "databasename";
    private $connect = null;

    function connect() {
        $this->connect = mysql_connect($this->host, $this->user, $this->pass) or die("Can't connect database");
        mysql_select_db($this->database, $this->connect);
    }

    function getData() {
        $data = array();
        $sql = 'Select * From test';
        $query = mysql_query($sql);
        while($row = mysql_fetch_assoc($query)) {
            $data[] = array($row['id'], $row['name']);
        }
        return $data;
    }

}
?>
Run Code Online (Sandbox Code Playgroud)

在index.php我有:

<?php
include 'db.php';
$connect = new connect();
$connect->connect();
$data = $connect->getData();
$str = '';
foreach ($data as $dt) {
    $str .= $dt[1];
}
echo $str;
?>
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:=> error: <b>Warning</b>: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource来自db.php.

我究竟做错了什么?

che*_*123 6

试着找出错误是什么:

  function getData() {
    $data = array();
    $sql = 'Select * From test';
    $query = mysql_query($sql);
    if(!$query) 
    {
     echo 'Error: ' . mysql_error(); /* Check what is the error and print it */
     exit;
    }

    while($row = mysql_fetch_array($query)) {  /* Better use fetch array instead */
        $data[] = array($row['id'], $row['name']);
    }
    return $data;
}
Run Code Online (Sandbox Code Playgroud)

  • 不知道为什么这被低估了.查询有问题,否则它将返回结果资源对象.找出的唯一方法是显示错误消息. (2认同)