0

I have the following snippet:

<?php
$query = mysql_query("SELECT * FROM users") or die(mysql_error());
echo "<table>";

while ($row = mysql_fetch_array($query))
{
    echo "<tr>";

    foreach($row as $value)
    {
        echo "<td>".$value."</td>";
    }

    echo "</tr>";

}

echo "</table>";?>

This snippet should, I think, output each piece of data from the table once. The problem is, I get it twice. So, for example

[email protected] [email protected] Joe Joe Bloggs Bloggs

Why might it be doing this?

3 Answers 3

6

By default, mysql_fetch_array does both numeric and associative (MYSQL_BOTH), giving you two keys each.

If you want numeric keys, use

while ($row = mysql_fetch_array($query, MYSQL_NUM))

if you want associative array, use:

while ($row = mysql_fetch_array($query, MYSQL_ASSOC))

Note also, that the mysql_* functions are deprecated and you should use MySQLi or PDO instead.

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

1 Comment

And a lesson was learned that day, thank you. Will mark as correct when timer permits.
0

change your code:

while ($row = mysql_fetch_assoc($query)) {
...

AND... mysql_* functions are deprecated, please consider moving to mysqli_* or PDO.

There, you will find possibilities to fetch one or all rows to an array...

  • with numeric indices only
  • with associative indices only
  • with both (--> double output in your case)

Comments

0

MySQL Fetch Array

The function by default uses MYSQL_BOTH which will give you an associative array along with a numbered array. For example:

Table:

name | emai
joe     [email protected]

The array returned will have

$row{
    [0] = "joe",
    ['name'] = "joe",
    [1] = "[email protected]",
    ['email'] = "[email protected]",
    }

You will have to use MYSQL_ASSOC or MYSQL_NUM as the second argument

NOTICE: Do not use MySQL_* functions for they have been deprecated as of PHP 5.5. Use PDO or MySQLi_* instead

Comments

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.