Jump to content

Display data from MySql


slj90

Recommended Posts

I'm trying to display data from a MySQL table using PHP.

 

At the minute it is repeating the frist row 23 times, there are 23 rows in the table. What do I need to add to my code to make it display each row?

 


$result=mysqli_query($con,"SELECT item_item_title, item_username FROM items");
$row = mysqli_fetch_array($result);
$item_item_title = $row[item_item_title];
$item_username = $row[item_username];

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo $item_item_title . "     -     " . $item_username . "<br>";
    }
} else {
    echo "0 results";
}

Thanks

Link to comment
Share on other sites

You need to fix the logic of your code. Right now, you fetch the first row (which may not even exist) and extract the item title and username. Then you iterate over the remaining rows, but you just keep echoing the title and username of the first row.

 

Get rid of the extra code for the first row and extract the title and name for each row within the loop.

Link to comment
Share on other sites

Try change to this

$result=mysqli_query($con,"SELECT item_item_title, item_username FROM items");

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo $row[item_item_title] . "     -     " . $row[item_username] . "<br>";
    }
} else {
    echo "0 results";
}
Edited by mlukac89
Link to comment
Share on other sites

  • 2 months later...

Hey,try this code:

$query="SELECT * FROM MY_TABLE";
$results = mysql_query($query);

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.