Dynamically populating a div with data from a MySQL table - php

Lets say I have a persons table :
forename surname age gender
--------------------------------------------
adam example 90 male
john example 90 male
If I wanted to display this information in separate divs, how could this be done? Say for example the following HTML.
<div class = "container">
<div class="wrapper">
<div class = "jumbotron">
<!-- adams data here -->
</div>
<div class = "jumbotron">
<!-- johns data here -->
</div>
</div>
</div>
I'm aware on how to query the DB to get the information into PHP variables, I'm just not sure how to dynamically display the data in separate divs.
Below is how I am getting the data
<?php
if($result = $db->query("SELECT forename,surname FROM users ")){
if($count = $result->num_rows){
while($row = $result->fetch_object()){
echo $row->forename, '<br><br>';
echo $row->surname, '<br><br>';
}
$result->free();
}
}
?>

Just wrap the div inside a loop so you'll print a div for each result row
<?php foreach($result as $r): ?>
<div class = "jumbotron">
<?php echo $r['name'] // Print fields you need ?>
</div>
<?php endforeach; ?>
EDIT: Now I can see your query. Try this:
<?php
if($result = $db->query("SELECT forename,surname FROM users ")){
if($count = $result->num_rows){
while($row = $result->fetch_object()){
?>
<div class = "jumbotron">
<?php echo $row->forename; ?><br><br>
<?php echo $row->surname; ?><br><br>
</div>
<?php
}
$result->free();
}
}
?>

Well Joe, This is a fairly simple problem that has probably been answered before.
I'll use the mysqli class of php
first create a mysqli connection object in a file for best practice then include it in your main script.
<?php
$connection = new mysqli($host_address, $username, $password, $database);
?>
include this in your main script
<?php require "path\to\connection\script"; ?>
<?php
$sql_adam = "SELECT * FROM persons WHERE forename = 'adam'";
$sql_john = "SELECT * FROM persons WHERE forename = 'john'";
$qry1 = $connection->query($sql_adam);
$qry2 = $connection->query($sql_john);
?>
<div class = "container">
<div class="wrapper">
<div class = "jumbotron">
<?php if ($qry1->num_rows >= 1){
while($adam = $qry1->fetch_assoc()){
foreach ($adam as $column => $data) {
echo "<p>$column : $data </p>";
}
}
}
</div>
<div class = "jumbotron">
<?php if ($qry2->num_rows >= 1){
while($john = $qry2->fetch_assoc()){
foreach ($john as $column => $data) {
echo "<p>$column : $data </p>";
}
}
}
</div>
</div>
</div>
Your Result should be something like
<div class = "container">
<div class="wrapper">
<div class = "jumbotron">
<p>forename : adam</p>
<p>surname : example</p>
<p>age : 90</p>
<p>gender : male</p>
</div>
<div class = "jumbotron">
<p>forename : john</p>
<p>surname : example</p>
<p>age : 90</p>
<p>gender : male</p>
</div>
</div>
</div>

Related

How to avoid blank first result when searching from databse

I have search webpage, but when the search is run, there is a blank first result.
<?php include "headnav.php";
$count = 0;
$sql = "SELECT * FROM lost_property";
if (!empty($_POST)) {
$name = mysqli_real_escape_string($dbconnect, htmlspecialchars($_POST['name']));
$item = mysqli_real_escape_string($dbconnect, htmlspecialchars($_POST['item']));
$area = mysqli_real_escape_string($dbconnect, htmlspecialchars($_POST['area']));
$sql = "
SELECT *
FROM lost_property
JOIN item
ON lost_property.itemID = item.itemID
JOIN area
ON lost_property.areaID = area.areaID
WHERE name LIKE '%$name%'
AND item LIKE '%$item%'
AND area LIKE '%$area%'
ORDER
BY lost_property.name ASC
";
$search_query = mysqli_query($dbconnect, $sql);
$count = mysqli_num_rows($search_query);
}
$result = $dbconnect->query($sql);
?>
<body>
<div class="form">
<h1>Search for lost property here:</h1>
<form action="" method="POST">
Name:
<input type="text" placeholder="Name" name="name">
Item type:
<select name="item" class="dropdown">
<option value="" disabled selected>Item</option>
<?php
$item_sql = "SELECT DISTINCT item FROM `lost_property`
JOIN item ON (lost_property.itemID = item.itemID)
ORDER BY item ASC
";
$item_query = mysqli_query($dbconnect, $item_sql);
$item_rs = mysqli_fetch_assoc($item_query);
do {
?>
<option value="<?php echo $item_rs['item']; ?>"><?php echo $item_rs['item']; ?></option>
<?php
} while ($item_rs = mysqli_fetch_assoc($item_query));
?>
</select>
Area (where it was found):
<select name="area" class="dropdown">
<option value="" disabled selected>Area</option>
<?php
$area_sql = "SELECT DISTINCT area FROM `lost_property`
JOIN area ON (lost_property.areaID = area.areaID)
ORDER BY area ASC
";
$area_query = mysqli_query($dbconnect, $area_sql);
$area_rs = mysqli_fetch_assoc($area_query);
do {
?>
<option value="<?php echo $area_rs['area']; ?>"><?php echo $area_rs['area']; ?></option>
<?php
} while ($area_rs = mysqli_fetch_assoc($area_query));
?>
</select>
<input type="submit" value="Search" name="btn">
</form>
</div>
<div class="gallery">
<h2>Search results:</h2>
<?php
//check for results. If there are none display error
if ($count < 1) {
?>
<div class="error">
<h1>No results were found.</h1>
</div>
<?php
} //end if
else {
do {
?>
<!-- display image and information from database and show in gallery -->
<div class="results">
<h3><?php echo $search_rs['name']; ?></h3>
<h3><?php echo $search_rs['item']; ?></h3>
<p><?php echo $search_rs['area']; ?></p>
</div>
<?php
} // end of do
while ($search_rs = mysqli_fetch_assoc($search_query));
} //end else
//if there are any display
?>
</div>
</table>
</body>
</html>
It's hard to see without any CSS, but no matter what is searched, there is always one result, but the h3 and p fields don't have any content. If there wasn't the no results error message it would pop up there too. What is causing this first result?
Use while (){}, if you use do instead it will run once first (credit to Magnus Eriksson).
It ends up like
else {
while ($search_rs = mysqli_fetch_assoc($search_query)) {
?>
<!-- display image and information from database and show in gallery -->
<div class="results">
<h3><?php echo $search_rs['name']; ?></h3>
<h3><?php echo $search_rs['item']; ?></h3>
<p><?php echo $search_rs['area']; ?></p>
</div>
<?php
} // end of do
} //end else
//if there are any display
?>
instead of
else {
do {
?>
<!-- display image and information from database and show in gallery -->
<div class="results">
<h3><?php echo $search_rs['name']; ?></h3>
<h3><?php echo $search_rs['item']; ?></h3>
<p><?php echo $search_rs['area']; ?></p>
</div>
<?php
} // end of do
while ($search_rs = mysqli_fetch_assoc($search_query));
} //end else
//if there are any display
?>

Using buttons to loop to the next element from the data fetched from database

I want to have a next button on my Productdetails.php page that would show the next image fetched from the database using while loop. Below is the productdetails.php page shows details of a particular product.
I am using simple php format, How can I go about it? I have come this far at this point.
<div class = "uniqueproduct">
<?php
if (isset($_GET['id']))
{
$id = $_GET['id'];
$query1 = mysqli_query($conn, "select * from products where PRODUCT_ID = $id");
while ($row1 = mysqli_fetch_array($query1)) {
?>
<div class = "singleproduct">
<?php echo '<img src = "data:image/jpeg;base64,'.base64_encode($row1['PRODUCT_IMAGE']).'" alt = "" width = "250px" height ="300px"/>'; ?>
</div>
<div class = "productName">
<?php echo $row1['PRODUCT_NAME']; ?>
</div>
<div class = "productDescription">
<?php echo $row1['PRODUCT_DESCRIPTION'];?>
</div>
<div class = "productPrice">
<?php echo $row1['PRODUCT_PRICE']; ?>
</div>
<?php
}
}
?>
<button class = "btnPicture"> ..............</button>
</div>

How to echo values in HTML that are coming from mysqli_multi_query in php

I am able to get values displayed from database when using mysqli_multi_query.But I am not able to print in my HTML code.Its Probably the issue with while loop. Below is my code which gives me the AVG for the three SQL statements. Only problem is with displaying average value in HTML.
<?php
$con = new mysqli("localhost", "root","","survey");
if ($con){ printf(""); }
$query = "SELECT AVG(workarea) FROM score;" ;
$query .= "SELECT AVG(manager) FROM score;";
$query .= "SELECT AVG(comm) FROM score;";
// Execute multi query
if (mysqli_multi_query($con,$query)) {
do {
if ($result=mysqli_store_result($con)) {
// Fetch one and one row
while ($row=mysqli_fetch_row($result)) {
printf("%s\n",$row[0]);
}
// Free result set
mysqli_free_result($result);
}
} while (mysqli_next_result($con));
}
?>
<div class="row count">
WORK AREA/UNIT SCORE : <?php echo $row[0]; ?> // echo $row[AVG(workarea)] doesnot work
</div>
<div class="row count">
SUPERVISOR/MANAGER SCORE : <?php echo $row[0]; ?> // echo $row[AVG(manager)]
</div>
<div class="row count">
COMMUNICATION SCORE : <?php echo $row[0]; ?> // echo $row[AVG(comm)] doesnot work
</div>
No need of multi query you just get AVG in single query. And write your html inside while loop as
$con = new mysqli("localhost", "root", "", "survey");
if ($con) {
printf("");
}
$query = "SELECT AVG(workarea),AVG(manager),AVG(comm) FROM score;";
// Execute multi query
if ($result = $con->query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
?>
<div class="row count">
WORK AREA/UNIT SCORE : <?php echo $row[0]; ?>
</div>
<div class="row count">
SUPERVISOR/MANAGER SCORE : <?php echo $row[1]; ?>
</div>
<div class="row count">
COMMUNICATION SCORE : <?php echo $row[2]; ?>
</div>
<?php
}
/* free result set */
$result->close();
}

Repeat div width with Different Database Table ID

I am trying to repeat a div the same div multiple times with as many rows as i have in the database table. a non working example i made of what i want is below.
<?php for ($i=0; $i < 3; $i++) {
?><!-- switch the three with the number of rows in the table-->
I would want to loop the container and switch the database query with the value of i.
<div id = "bodyContainer">
<form class="review">
<div class="reviewContainer">
<div class = "images">
<?php
$link = mysqli_connect("localhost", "root", "root","DJP");
if (mysqli_connect_error()) {
die("Could not connect to database");
}
$query = "SELECT * FROM reviews WHERE id = '<?php echo $i ?><!--switch the value of i here-->'";
$result=mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
echo '<img height = 90% width = 100% src="data:image/jpeg;base64,'.$row[3].' " />';
?>
</div>
<!--<div class="title">
<?php
//echo $row[1];
?>
</div>-->
<div class = "comment">
<?php
echo $row[2];
?>
</div>
<div class = "rating" style = "float: right;">
<?php
echo $row[4];
?>
<br/>
<br/>
stars
</div>
</div><!--end review-->
</form>
</div><!--end body container-->
<?php;}?><!-- end the for loop so all the divs can be re-done with a new entry for the query. I would move the $link out of loop also.-->
Just fetch all the rows once and then go through them as you print the data:
$link = mysqli_connect("localhost", "root", "root","DJP");
if (mysqli_connect_error()) {
die("Could not connect to database");
}
$query = "SELECT * FROM reviews";
$result=mysqli_query($link, $query);
while($row = mysqli_fetch_array($result)){ ?>
<div id = "bodyContainer">
<form class="review">
<div class="reviewContainer">
<div class = "images">
<?php
echo '<img height = 90% width = 100% src="data:image/jpeg;base64,'.$row[3].' " />';
?>
</div>
<!--<div class="title">
<?php
//echo $row[1];
?>
</div>-->
<div class = "comment">
<?php
echo $row[2];
?>
</div>
<div class = "rating" style = "float: right;">
<?php
echo $row[4];
?>
<br/>
<br/>
stars
</div>
</div><!--end review-->
</form>
</div><!--end body container-->
<?php } ?>

Data not displaying from database

I am new to PHP and trying to display data from the database.
However it only displays data from one row but I want to show the data from multiple rows where the condition match. Here is my code I am using:
<?PHP
session_start();
if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) {
header ("Location: checklogin.php");
}
$con = mysqli_connect("localhost", "root", "", "map_my_way");
$fetch_row = $_SESSION['username'];
$result = mysqli_query($con,"SELECT * FROM members where username='$fetch_row'");
while($row = mysqli_fetch_array($result)) {
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$email = $row['email'];
$m_no = $row['m_no'];
$v_name = $row['v_name'];
$capacity = $row['capacity'];
$fuel_type = $row['fuel_type'];
}
$result2 = mysqli_query($con,"SELECT s_a_name FROM locations where username='$fetch_row'");
$row2 = mysqli_fetch_array($result2);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Profile Page</title>
<link rel="stylesheet" type="text/css" href="profile.css">
</head>
<body id="body">
<div id="mmw"> <span> MAP MY WAY </span></div>
<div id="title_box">
<button id="lvbutton">My Profile</button>
<button id="lvbutton">Maps</button>
<button id="lvbutton">Edit Profile</button>
<button id="lvbutton" style="float:right; margin- right:10px;">Sign-Out</button>
</div>
<div id="box">
<div id="name_box"><span>Welcome <?php echo($_SESSION['username']); ?></span></div>
<div id="box1">
<div> <p id="link">Your Information </p>
<ul style="margin-top:20px; padding-left:0;">
<li><span>First Name : <?php echo $first_name; ?></span></li><br>
<li><span>Last Name : <?php echo $last_name; ?></span></li><br>
<li><span>Email : <?php echo $email; ?></span></li><br>
<li><span>Age : <?php echo $m_no; ?></span></li><br>
<li><span>Current Vehical : <?php echo $v_name; ?></span></li><br>
<li><span>Fuel Type: <?php echo $fuel_type; ?> </span></li><br>
<li><span>Seating Capacity : <?php echo $capacity; ?></span></li><br>
</ul>
</div>
</div>
<div id="box2"> <p id="link">Saved Routes </p>
<ul style="margin-top:20px;">
<span> <?php foreach($row2 as $data)
{echo "route Name : $data <br>" ; };
?>
</span>
</ul>
</div>
</div>
</div>
</body>
</html>
Your query on the members table is only going to return one row, so you don't really need to have $row = mysqli_fetch_array($result) in a loop (that shouldn't break your script, though). Your query on the locations table will potentially return more than one row, so you do need to loop on that one. Something like:
$result2 = mysqli_query($con,"SELECT s_a_name FROM locations where username='$fetch_row'");
$savedRoutes = "";
while($row2 = mysqli_fetch_array($result2))
{
$savedRoutes .= "route Name : " . $row2['s_a_name'] . "<br/>";
}
will put all the data together in a string ($savedRoutes) that can be echoed down in the "Saved Routes" section of your html code.
Alternatively, you can put the loop down in the "Saved Routes" section and just echo out each line as you loop through. Personally I think putting the loop in the top and concatenating the data into a string is a bit cleaner and easier to read.

Categories