Reputation: 95
I just registered here and I'm in search for help. I am a newbie in programming, but I do have some basic knowledge in programming and I am eager to learn PHP and MySQL and such languages.
I need help modifying PHP code that displays data from database in separated div elements.
Here is the code:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = $_REQUEST['upit'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<div class='proizvodi'>";
// output data of each row
$result->data_seek(0);
while($row = $result->fetch_assoc()) {
echo "<div class='row'>";
foreach($row as $key => $value){
echo $value;
}
echo "</div>";
echo "<hr />";
}
echo "</div>";
}
else {
echo "<div class='search-query-none'><img src='index/no result.png' width='754' height='198' /></div>";
}
$conn->close();
?>
Now how should I modify the code so that it will display data from each column inside a div with a class name that holds the name of the column in database?
I kind of understand this piece of code, but I don't understand some keywords such as fetch_assoc()
and so, but I will learnt them with time.
I would really appreciate if you could help me, and please tell me if you're missing some information, since this is my first question here and I will gladly update the question with necessary information. Thank you!
****EDIT** Here's is the fix:**
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = $_REQUEST['upit'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<div class='proizvodi'>";
// output data of each row
$result->data_seek(0);
while($row = $result->fetch_assoc()) {
echo "<div class='row'>";
foreach($row as $key => $value){
echo "<div class='" . $key . "'>" . $value . "</div>";
}
echo "</div>";
echo "<hr />";
}
echo "</div>";
}
else {
echo "<div class='search-query-none'><img src='index/no result.png' width='754' height='198' /></div>";
}
$conn->close();
?>
Upvotes: 2
Views: 72
Reputation: 78
You'll want to move the echo "<div class='row'>";
into the inside of the foreach loop; and then instead of class='row', you can say this:
echo "<div class='{$key}'>{$value}</div>";
or
echo "<div class='" . $key . "'>" . $value . "</div>";
(The first approach plops the variables' values straight down into the string; the second concatenates them - the effect is the same.)
Upvotes: 2