-2

Possible Duplicate:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result

In db.php I have:

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

}
?>

In index.php I have:

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

I am getting the following error: => error: <b>Warning</b>: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource from db.php.

What am I doing wrong?

2
  • I tried to copy paste your code, No Error Found ! Please check your database name, database password, database user or table name. Commented Dec 19, 2011 at 3:57
  • As a rule of thumb, you shouldn't name a local variable the same as your class: 'connect'. Change 'private $connect' to (for instance) 'private $connection'. Then you should use that variable in your query: $query = mysql_query($sql, $this->connection); Commented Dec 19, 2011 at 11:40

3 Answers 3

6

Try to find what is the error:

  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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Don't know why this was downvoted. Something is wrong with the query or else it would return a result resource object. Only way to find out is to display the error message.
I bet the error message is one of the two things I mentioned :P
2

That error is telling you that your query executed by $query = mysql_query($sql); is returning an error. It's not returning zero results, it's returning an error which suggests that your database named 'databasename' or table within that named 'test' doesn't exist.

Comments

0

It sounds like no results are returned from the query or a general query error, do the columns and table in the query exist and is your connection to the database all okay?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.