0

I am trying the following code:

<?php

    $link = mysql_connect('localhost', 'root', 'geheim');
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }
    echo 'Connected successfully';



    $query = "SELECT * FROM Auctions";
    $result = mysql_query($query);

    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
        foreach($row as $field=>$value)
        {
            echo "$field: {$value} <br />";
        }
    }
    mysql_close($link);

?> 

And get this error:

Warning: mysql_fetch_array(): supplied argument is not a
    valid MySQL result resource in
    C:\Programme\EasyPHP 2.0b1\www\test.php on line 14

What am I missing?

1

4 Answers 4

9

You haven't selected a database - use mysql_select_db()

That would be something like:

<?php
    $link = mysql_connect('localhost', 'root', 'geheim');
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }
    echo 'Connected successfully';

    $db_selected = mysql_select_db('foo', $link);
    if (!$db_selected) {
        die ('Error selecting database: '. mysql_error());
    }
    echo 'Using database successfully';

    $query = "SELECT * FROM Auctions";
    $result = mysql_query($query);
    while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        foreach($row as $field=>$value) {
            echo "$field: {$value} <br />";
        }
    }
    mysql_close($link);
?> 
Sign up to request clarification or add additional context in comments.

Comments

2

Your MySQL query possibly does not match any rows in the database.

Check the return value of mysql_query(), which returns "resource" on success and "false" on failure.

$query = "SELECT * FROM Auctions"; 
$result = mysql_query($query);

if ($result !== false) {
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { 
        foreach ($row as $field=>$value) { 
            echo $field . ':' . $value
        }
    }
} else {
    // query returned 0 rows
}

As others also suggested, you can use mysql_error() to look if the query returns any mySQL errors

1 Comment

mysql_query only returns false on an actual error. An empty result set is not an error.
1

$query = "SELECT * FROM Auctions";

$result = mysql_query($query) or die(mysql_error());

so you'll see the error

Comments

0

Are you getting anything returned? If no results are found, mysql_query returns FALSE.

Check that before running fetch_array.

1 Comment

If no results are found, it still returns a resource, but there are no results in it. mysql_query() only returns false if there is an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.