0

Hey so i am trying to grab data from mysql database and i am getting double the data in my table when i grab the data from mysql?

Here is the code i am using to make the graph.

$query = "SELECT id,username FROM users";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
    foreach($row as $id => $val)
    {
        echo 
        "<tr>
        <td>" . $row['id'] . "</td>
        <td>" . $row['username'] . "</td>
        <td></td>
        <td></td>
        </tr>";
    }
}

This is the result: enter image description here

Terrii
  • 385
  • 4
  • 8
  • 23

3 Answers3

1

Use onli sing loop...while loop or foreach...you are using both the loops e.g foreach inside while..Use that

$query = "SELECT id,username FROM users";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{

        echo 
        "<tr>
        <td>" . $row['id'] . "</td>
        <td>" . $row['username'] . "</td>
        <td></td>
        <td></td>
        </tr>";

}
Ankit Chugh
  • 198
  • 1
  • 11
1

Use only single loop

while($row = mysql_fetch_assoc($result))
{
      echo 
        "<tr>
        <td>" . $row['id'] . "</td>
        <td>" . $row['username'] . "</td>
        <td></td>
        <td></td>
        </tr>";
}

instead of double loop

while($row = mysql_fetch_assoc($result))
{
    foreach($row as $id => $val)
    {
        echo 
        "<tr>
        <td>" . $row['id'] . "</td>
        <td>" . $row['username'] . "</td>
        <td></td>
        <td></td>
        </tr>";
    }
}
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
1

Use "mysql_fetch_array" instead of "mysql_fetch_assoc":

$query = "SELECT id,username FROM users";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
    echo 
    "<tr>
    <td>" . $row['id'] . "</td>
    <td>" . $row['username'] . "</td>
    <td></td>
    <td></td>
    </tr>";
}
Partha Mitra
  • 130
  • 7