0

I'm trying to get an array of id's from my database and then be able to echo out each id. Something like this:

$query = mysql_query("SELECT id FROM TableName WHERE field = 'test' ORDER BY id DESC") or die(mysql_error());

$row = mysql_fetch_array($query);

echo "array: ".$row[1]." <br>";
echo "array: ".$row[2]." <br>";
echo "array: ".$row[3]." <br>";

This doesn't seem to be working though?

2
  • 1
    Table is a reserved word and must be in backticks. What error do you get? Commented May 8, 2012 at 21:37
  • Oops, I changed the name - I'm not normally using the name Table.. Commented May 8, 2012 at 21:38

2 Answers 2

2

The problem is that mysql_fetch_array fetches an ARRAY, which is 0-based. You're fetching a single field from the database, which will be stored at $row[0] in your result array. Since you're echoing out only row[1] through row[3], you'll never see the result:

$row = mysql_fetch_array($query);
print_r($row);

should give you:

Array (
    0 => 'id_field_value_here'
)

and

echo $row[0]

would also output

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

Comments

1

mysql_fetch_array fetches 1 row. You need to do something like

...
$res = array();
while ($row = mysql_fetch_array($query))
{
  $res[] = $row;
}
//now $res[0] - 1st row, $res[1] - 2nd, etc  

1 Comment

Thanks this was indeed the problem :)

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.