简体   繁体   中英

PHP - output associate array into HTML <div>s with labels/headings

I have a PHP function that returns a single row from a localhost MySQL table like so:

<?php
//include database connection process
require_once("includes/conn.inc.php");
//prepare statement
$stmt = $conn->prepare("Select * FROM races WHERE raceID = ?");
$id = 1;
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
?>

What I would like to do with this array is output the data from the individual fields in their own HTML <div> or <p> with a heading indicating what they mean in a separate div. I currently user the print_row method that outputs everything in one. All the data I want is there, but I'd like it separated out into name/value paragraphs or divs.

//what I currently have
<?php
    print_r($row);
?>

Is there a way to do this?

Thanks in advance,

Mark

I didn't understand the question very well but I think I understand what you need.

Use while to iterate trough each row.

while($row = $resultDesc->fetch_assoc())
{
    echo '<p><strong>Description:</strong></p> ';
    echo '<p>'. $row['description'] . '</p>';
}

That's not the exact solution but atleast shows you the path.

You can use foreach

<?php foreach ($row as $key => $val): ?> 
    <p><strong><?php echo $key; ?>:</strong></p> 
    <p>
        <?php
            //output relevant attribute
            //of query run on page load
            echo $val;
        ?>
    </p>
<?php endforeach; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM