Page 1 of 1

Why won't this code cycle through the database?

Posted: Tue Jun 23, 2009 1:48 pm
by pkunzipula
Hello All!

I am very new to PHP. What I'm trying to do is retreive the Headline and Text of 8 stories in a database. I want to display 1 story at a time in the #SLIDE div, which changes based on which div in #BUTTONS the user clicks. The show/hide effects are working, but what I cannot figure out is how to make PHP display 8 unique records. Right now, it displays the first record 8 times. I have copied examples Verbatim from books to no avail.


Here is the Body code

Code: Select all

<div id="headlines">
   <div id="slide">
      <div id="p1">
         <h1><?php echo $headline; ?></h1>
         <p><?php echo $story; ?></p>
      </div>
      <div id="p2">
         <h1><?php echo $headline; ?></h1>
         <p><?php echo $story; ?></p>
      </div>
   </div> <!-- end slide -->
   <div id="buttons">
         <h2>Latest News</h2>
            <?php
    for ($z=1; $row = $result->fetch_assoc(); $z++) { ?>
            <div id="b<?php echo $z ?>"><?php echo $headline; ?></div>
            <?php } ?>
   </div> <!-- end buttons -->       
</div><!-- end #headlines -->
And here is the HEAD code

Code: Select all

//create a connection to MySQL
$conn = dbConnect('query');
//get total number of records
$getTotal = 'SELECT COUNT(*) FROM topstories';
//submit query and store results as totalStories
$total = $conn->query($getTotal);
$row = $total->fetch_row();
$totalStories = $row[0];
//prepare SQL to retrieve topstories details
$sql = 'SELECT * FROM topstories';
//submit the query
$result = $conn->query($sql) or die(mysqli_error());
//extract the first record as an array
$row = $result->fetch_assoc();
//get the headline and text of the first story
$headline = $row['headline'];
$story = $row['story'];
Could somebody PLEASE explain what is wrong with this?

I thank you for your time.

Arlen

Re: Why won't this code cycle through the database?

Posted: Tue Jun 23, 2009 2:47 pm
by Christopher
Try:

Code: Select all

<?php
    $z=1;
    while ($row = $result->fetch_assoc()) {
            echo "<div id=\"b$z\">$headline</div>";
            ++$z;
    }
?>

Re: Why won't this code cycle through the database?

Posted: Tue Jun 23, 2009 3:40 pm
by pkunzipula
Christopher,

I thank you for your reply.

I tried your code, but it produced the same result.

It then occurred to me that I cannot echo $headline, I must echo $row['headline']. And now it's working.

Sort of.

Thanks again.