Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (6.1k points)

I need to loop through each result from the mysql table and generate html div for each row. The database table looks like below:

--------------------------------
  id   |  color  | width | img
--------------------------------
   1   |  red    |  550  | url
--------------------------------
   2   |  black  |  650  | url
--------------------------------

I have an opinion of how this might work but not sure about the syntax. 

Following is my attempt.

<?php
// connect to the database

$rows = // get rows from the db table

foreach ($rows) {
<div style="background-color:$color;width:$width;">
    <img src="$img">
</div>
}

1 Answer

0 votes
by (12.7k points)

Following is a simplistic example with a simple query:

<?php

$mysqli = new mysqli("db_host", "db_user", "db_password", "db_name");

// check connection
if ($mysqli->connect_errno) {
    die("Connect failed: ".$mysqli->connect_error);
}

$query = "SELECT * FROM imgs";
$result = $mysqli->query($query);

while($row = $result->fetch_array()){
echo '<div style="background-color:'.$row[color].';width:'.$row[width].';"><img src="'.$row[img].'"></div>';

Want to be a SQL expert? Come and join this SQL Certification course by Intellipaat.

Related questions

0 votes
1 answer
asked Jan 1, 2021 in SQL by Appu (6.1k points)
0 votes
1 answer
asked Dec 31, 2020 in SQL by Appu (6.1k points)
0 votes
1 answer
asked Aug 14, 2019 in Web Technology by Sammy (47.6k points)

Browse Categories

...