0

I'm using PHP 5 with mySQL:

$line = mysql_fetch_array($result, MYSQL_ASSOC);

When I do this, I can see the results of the query printed:

foreach ($line as $data)
    {
        echo ($data . ", ");
    }

But if I do this instead:

echo ($line[0] . " " . $line[1] . " " . $line[2]);

I don't see anything. Also I can't assign a value from $line:

$values[] = $line[0]; // fails - doesn't assign anything

Why? And what should I be doing instead?

2
  • While you're developing, turn on all errors with error_reporting(E_ALL). You would then see some E_NOTICE level errors about undefined array indexes Commented Nov 11, 2011 at 1:28
  • the result from the mysql query are not 0-indexed array , instead the keys are the culomn names of the DB tables Commented Nov 11, 2011 at 17:31

3 Answers 3

5

You've nominated to retrieve records as associative entries only (MYSQL_ASSOC). This means your $line array will not contain numeric indices.

If you only want numeric arrays, use mysql_fetch_row().

Associative only, mysql_fetch_assoc()

You can also retrieve a mixed numeric and associative array using mysql_fetch_array($result, MYSQL_BOTH) however this will give you duplicate entries in your foreach loop.

Sign up to request clarification or add additional context in comments.

Comments

0

You told MySQL that you want to fetch the row as an array, which means $line is not a 0-index array, it's an associative array, which means the keys of the array are the column names of the table(s) you selected from.

var_dump($line); // Will display the keys

Comments

0

try:

echo ($line["id"] . " " . $line["id"] . " " . $line["id"]);

so instead of using a index number like [0] you use the corresponding column-name

1 Comment

That would only be possible using mysql_fetch_object() or by casting the associative array to (object)

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.