Ctrl_Alt_Defeat
Ctrl_Alt_Defeat

Reputation: 4009

Render data from PHP DB query in HTML

I am a newbie to PHP but trying to learn it to enhance my programming skillset

So far i have the following PHP code in my page to return some data from my Database:

<?php
            //code missing to retrieve my data
            while($row = mysql_fetch_array($result))
            {
                echo '$row['Name']';
            }

            mysql_close($connection);
?>

This is working in that I can see the names from my database displayed on screen. I have seen as well that I can include html in the echo to format the data. However if I have the html code like below in a jQuery accordion outside my PHP code in the page - how can I dynamically place the Names in the specific h3 tags - so the first name in my table is Joe so that comes back in [0] element of array - is there a way I can reference this from my html code outside the php?

<div id="accordion">
  <h3>Joe</h3>
  <div>
    <p>
     Some blurb about Joe
    </p>
  </div>
  <h3>Jane</h3>
  <div>
    <p>
     Some blurb about Jane
    </p>
  </div>
  <h3>John</h3>
  <div>
    <p>
    Some Blurb about John.
    </p>
  </div>
</div>

Upvotes: 0

Views: 227

Answers (3)

Harshal
Harshal

Reputation: 3622

Like this :

    <div id="accordion">
    <?php
    while($row = mysql_fetch_array($result))
    {
      <h3><?php echo $row['Name'] ?></h3>
      <div>
        <p>
         Some blurb about Joe
        </p>
      </div>
    } ?>
    </div>

Upvotes: 0

miltos
miltos

Reputation: 1019

add your html in while loop like this

<?php
        //code missing to retrieve my data
        while($row = mysql_fetch_array($result))
        {
?>
<h3><?php echo $row['Name']?></h3>
  <div>
    <p>
     Some blurb about <?php echo $row['Name']?>
    </p>
  </div>
<?php
        }

        mysql_close($connection);
?>

Upvotes: 0

Jeff Lambert
Jeff Lambert

Reputation: 24671

Try something like this:

<?php while($row = mysql_fetch_array($result)) { ?>
    <h3><?php echo $row['name']; ?></h3>
    <div>
        <p>Some blurb about Joe</p>
    </div>
<?php } ?>

I'm assuming 'Some blurb about Joe' would also have to be replaced by a field in the DB, which you can accomplish in the same manner as the name.

@Gert is correct - the original mysql API is deprecated and should not be used anymore. Look into mysqli or PDO, instead.

Upvotes: 1

Related Questions