user2099810
user2099810

Reputation: 381

MySQL row being outputted twice

I need to output a name from the last added row of my table, and it works sort of, it outputs the correct data twice. So instead of name1 it gives me name1name1. I'm still a novice with PHP but i think there is a double loop somewhere in this piece of code which is giving me a hard time, but i'm still unable to locate where that is..

If someone can give me a pointer that would be greatly appreciated.

    <?php $query="SELECT question FROM poll ORDER BY id DESC LIMIT 1";
    $results = mysql_query($query);

    while ($row = mysql_fetch_array($results)) {
       echo '<tr>';
          foreach($row as $field) {
       echo '<td>' . htmlspecialchars($field) . '</td>';
    }
       echo '</tr>';
    } ?>

Upvotes: 0

Views: 91

Answers (3)

Mark Baker
Mark Baker

Reputation: 212402

By default, mysql_fetch_array() returns values both as associative and as enumerated (MYSQL_BOTH); specify either one or the other

while ($row = mysql_fetch_array($results, MYSQL_ASSOC)) {

EDIT

But the mysql extension is old and deprecated, and you really should be switching to mysqli or pdo with prepared statements and bind variables. If you're just learning, then it's best to learn the right methods with the right extensions from the start

Upvotes: 3

Andizer
Andizer

Reputation: 344

I would use mysql_fetch_assoc. Because this will only fetch the results as an associative array.

$query="SELECT question FROM poll ORDER BY id DESC LIMIT 1";
$results = mysql_query($query);

while ($row = mysql_fetch_assoc($results)) {
   echo '<tr>';
   foreach($row as $field) {
       echo '<td>' . htmlspecialchars($field) . '</td>';
   }
   echo '</tr>';
}

Upvotes: 1

Sougata Bose
Sougata Bose

Reputation: 31739

No need of the while. You are fetching a single row. And use mysql_fetch_assoc for associative array

$row = mysql_fetch_assoc($results);

echo '<tr>';
foreach($row as $field) {
   echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';

Upvotes: 2

Related Questions