Intellipaat 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
0 votes
3 answers
0 votes
2 answers
0 votes
1 answer

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...