I have two tables one for users and one for their reviews. On one page I need to show thumbnails of each user and the reviews that match that user. The problem is the LEFT JOIN creates a row for every time there is a review. So if a user has two reviews they are showing up twice in the list of thumbnails. Do I need a loop inside the loop? Everything I can think of seems really clunky. Thanks.
// Get Data
$qry = "SELECT * FROM `users` LEFT JOIN `reviews` ON users.userId = reviews.user_id WHERE installation_id = $installation_id";
$res = mysqli_query($mysqli, $qry) or die('-1'.mysqli_error($mysqli));
//$uqry = "SELECT membership FROM users WHERE userId = $uid";
//$current_user = mysqli_query($mysqli, $uqry) or die('-1'.mysqli_error($mysqli));
$getUser = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT membership FROM users WHERE userId = $uid"));
$currentUserLevel = $getUser['membership'];
?>
<div class="container">
<div class="content">
<?php if ($msgBox) { echo $msgBox; } ?>
<div class="row">
<?php $lists = array();
while($list = mysqli_fetch_assoc($res)) {
$lists[] = $list;
}
foreach($lists as $list) {
$name = stripslashes($list['usersName']);
$bio = stripslashes($list['usersBio']);
$review = stripslashes($list['comments']);
$stars = stripslashes($list['stars']); ?>
<div class="col-md-4">
<div id = "user-square">
<div class="avatar">
<img src="<?php echo $avatarDir.$list['usersAvatar']; ?>" class="publicAvatar" />
</div>
Name:<?php echo $name; ?> <br />
Bio:<?php echo $bio; ?> <br />
Review:<?php echo $review; ?> <br />
Stars: <?php echo $stars; ?> <br />
<?php
if ($currentUserLevel == 'pro') {
echo 'CONTACT SCOUT';
}
else {
echo 'Sorry you must upgrade to a Pro membership to contact this Scout';
}
?>
</div>
</div>
<?php }
?>
</div>
</div>
</div>
</div>
Change the while loop to the following:
while($list = mysqli_fetch_assoc($res)) {
$lists[$list['usersName']][$list['usersBio']][$list['stars']][] = $list['comments'];
}
That will give you a nice multidimensional array with the user name as the first key, and all that users reviews ordered by star rating. You should probably use a unique key rather than the users name as there could be duplicates, so either the email or unique row ID would be better.
You can then (VERY basic example):
$reviews = "";
foreach($lists as $username => $array) {
foreach($array as $bio => $array2) {
$name = stripslashes($username);
$bio = stripslashes($bio);
foreach($array2 as $stars => $comments_array) {
$stars = stripslashes($stars);
foreach($comments_array as $comments) {
$reviews .= $stars . " - " . stripslashes($comments) . "<br />";
}
}
// Your HTML here using $name, $bio, and $reviews(which will be star rating followed review for that user each on a new line)
echo '
<table width="400">
<tr>
<td>' . $name . '</td><td>' . $bio . '</td><td>' . $reviews . '</td>
</tr>
</table>
';
}
$reviews = "";
}
Related
I have the following code. How do I show the first image in the database with index of 0 for the large image display at end of the code? Right now it is showing the last image in the database.
<div id="imgWheel" class="treatmentContainer">
<?php
$query = "SELECT * FROM images WHERE user = 0 ORDER BY id;";
$result = $mysqli->query($query);
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$product = $row["product"];
$room = $row["room"];
$style = $row["style"];
$tags = $row["tags"];
$src = $row["url"];
$dataid = $row["id"];
$imgClass = "";
if (in_array($src, $favourites)) {
$imgClass = " favourite";
}
echo "<div class='treatment$imgClass' data-url='$src' data-product='$product' data-room='$room' data-style='$style' data-tags='$tags' data-number='$dataid' id='pic_$dataid' >";
echo "<img src='$src' crossorigin='anonymous'/>";
echo "</div>";
}
?>
</div> <!-- close imgWheel -->
<!-------- Large Image Display------- -->
<div id="display">
<img id="mainImage" src="<?php echo $src ?>" />
</div>
Your result set is alreadyx ordered by id, so you need only a variable, to be filled once with the first imageurl
<div id="imgWheel" class="treatmentContainer">
<?php
$bigpictureurl = "";
$query = "SELECT * FROM images WHERE user = 0 ORDER BY id;";
$result = $mysqli->query($query);
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$product = $row["product"];
$room = $row["room"];
$style = $row["style"];
$tags = $row["tags"];
$src = $row["url"];
$dataid = $row["id"];
if (empty($bigpictureurl)) {
$bigpictureurl = $src ;
}
$imgClass = "";
if (in_array($src, $favourites)) {
$imgClass = " favourite";
}
echo "<div class='treatment$imgClass' data-url='$src' data-product='$product' data-room='$room' data-style='$style' data-tags='$tags' data-number='$dataid' id='pic_$dataid' >";
echo "<img src='$src' crossorigin='anonymous'/>";
echo "</div>";
}
?>
</div> <!-- close imgWheel -->
<!-------- Large Image Display------- -->
<div id="display">
<img id="mainImage" src="<?php echo $bigpictureurl ?>" />
</div>
You just need to update your SQL query, just add LIMIT 1. This will limit the result just to 1 record and as you have ORDER id ASC, it will show the first record of the given user (as per you it is 0).
$query = "SELECT * FROM images WHERE user = 0 ORDER BY id ASC LIMIT 1;";
A quick and dirty solution is to save your first image in some separate variables, for example like this:
$isFirst = true;
$firstImageSrc = "";
$result = ....;
while (...) {
// set your $product, $room etc here
if ($isFirst) {
$isFirst = false;
$firstImageSrc = $src;
}
}
echo ...
?>
</div> <!-- close imgWheel -->
<!-------- Large Image Display------- -->
<div id="display">
<img id="mainImage" src="<?php echo $firstImageSrc ?>" />
</div>
A much more elegant solution would be to create an array with all your images, so that you can separate your php from your html. I will refactor your code below, and fix your first image problem as well:
<?php
$images = [];
$idx = 0;
$query = "SELECT * FROM images WHERE user = 0 ORDER BY id;";
$result = $mysqli->query($query);
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$images[$idx]["product"] = $row["product"];
$images[$idx]["room"] = $row["room"];
$images[$idx]["style"] = $row["style"];
$images[$idx]["tags"] = $row["tags"];
$images[$idx]["src"] = $row["url"];
$images[$idx]["dataid"] = $row["id"];
$images[$idx]["imgClass"] = "";
if (in_array($src, $favourites)) {
$images[$idx]["imgClass"] = " favourite";
}
$idx++;
}
?>
<div id="imgWheel" class="treatmentContainer">
<?php foreach ($images as $image) { ?>
<div class='treatment<?=$image["imgClass"]?>' data-url='<?=$image["src"]?>' data-product='<?=$image["product"]?>' data-room='<?=$image["room"]?>' data-style='<?=$image["style"]?>' data-tags='<?=$image["tags"]?>' data-number='<?=$image["dataid"]?>' id='pic_<?=$image["dataid"]?>' >
<img src='<?=$image["src"]?>' crossorigin='anonymous'/>
</div>
<?php } ?>
</div> <!-- close imgWheel -->
<!-------- Large Image Display------- -->
<div id="display">
<img id="mainImage" src="<?=$images[0]["src"]?>" />
</div>
Since you have all of that in your WHILE statement, I assume you want to echo all those records. And then at the end show the 1st pic. So for the "Large Image Display," give this a try:
<div id="display">
$query = "SELECT * FROM images WHERE user = 0;";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC)
$src = $row["url"];
<img id="mainImage" src="<?php echo $src ?>" />
</div>
If you'd like less code, then save the value of $src inside your WHILE loop when user=0 into some other variable like $src2. And then your code simply becomes:
<img id="mainImage" src="<?php echo $src2 ?>" />
How can I set fetch to show only one value, per user?
Now, my fetch shows all rows, but I want to foreach only for 1 row
Ex: Headshots row: foreach headshots row
Deaths row: Foreach deaths row
Currently my code shows every row and I can't put them into html
PHP.
<?php
include_once 'config.php';
$top_users = [];
$columns = ['Humanity', 'Headshots', 'Murders', 'BanditsKilled', 'ZombiesKilled', 'pAliveTime'];
foreach ($columns as $column) {
$query = $config->prepare("SELECT UserID, UserName, $column as num FROM users ORDER BY $column DESC LIMIT 1");
if($query->execute()) {
$top_users[$column] = $query->fetch();
}
}
?>
HTML
<div class="colw_3 spec-l border-right">
<p></p><p><strong><em><font color="white">Humanity</font></em></strong><br>
</p>
<p><strong><em><font color="white">Headshots:</font></em></strong><br>
</p>
<p><strong><em><font color="white">Bandits Killed:</font></em></strong><br>
</p>
<p><strong><em><font color="white">Murders</font></em></strong><br>
</p>
<p><strong><em><font color="white">Zombies Killed</font></em></strong><br>
</p>
<p><em><strong><font color="white">Alive Time:</font></strong></em><br>
</p>
</div>
<!-- END col_6 -->
<div class="colw_3 paddbott100 spec-r">
<p></p><p><strong><font color="white"> <?php foreach ($top_users as $column => $data) {
echo $data['UserName'] . ' ' . $data['num'] ;
}?></font></strong><br>
</p>
<p><strong><font color="white"> <?php echo $query_result["Headshots"]; ?></font></strong><br>
</p>
<p><strong><font color="white"> <?php echo $query_result["BanditsKilled"]; ?></font></strong><br>
</p>
<p><strong><font color="white"> <?php echo $query_result["Murders"]; ?></font></strong><br>
</p>
<p><strong><font color="white"> <?php echo $query_result["ZombiesKilled"]; ?></font></strong><br>
</p>
<p><strong><font color="white"> <?php echo $query_result["pAliveTime"]; ?></font></strong><br>
</p>
</div>
and instead of ?php echo $query_result["text"]; i want to add the foreach, but it shows all rows.
I think to add
foreach ($top_users as $column => $data)
{{ $row->Humanity }}
but i don't know how to type it.
I tried to do so:
<?php
include_once 'config.php';
$top_users = [];
$Humanity = ['Humanity'];
$Headshots = ['Headshots'];
$Murders = ['Murders'];
$BanditsKilled = ['BanditsKilled'];
$ZombiesKilled = ['ZombiesKilled'];
$pAliveTime = ['pAliveTime'];
foreach ($Humanity as $Humanity) {
$query = $config->prepare("SELECT UserName, $Humanity as num FROM users ORDER BY $Humanity DESC LIMIT 1");
if($query->execute()) {
$top_users[$Humanity] = $query->fetch();
}
$query = $config->prepare("SELECT UserName, $Headshots as num FROM users ORDER BY $Headshots DESC LIMIT 1");
if($query->execute()) {
$top_users[$Headshots] = $query->fetch();
}
}
?>
HTML
<div class="colw_3 paddbott100 spec-r">
<p></p><p><strong><font color="white"> <?php foreach ($top_users as $Humanity => $data) {
echo $data['UserName'] . ' ' . $data['num'] . '<br>' ;
}?></font></strong><br>
</p>
<p><strong><font color="white"> <?php foreach ($top_users as $Headshots => $data) {
echo $data['UserName'] . ' ' . $data['num'] . '<br>' ;
}?></font></strong><br>
Hello so i made my filter system its a simple one only location and price range are set for now everything looks like this :
so the problem i have is that min and max price range filter doesn't work location filter are working as it should be the only problem i face is min and max price got no error or warning nothing but eater nothing happens to.
php code above :
$cat1 = '';
if(isset($_GET["catid"])){
$p1 = '';
$p2 = '';
$catid = $_GET["catid"];
$l1 = substr($catid,0,1);
$l2 = substr($catid,1,1);
$p1 = "CAT".$l1;
if(!empty($l2)){
$p2 = "CAT".$l1."-".$l2;
$p3 = $p2;
}
$cat1 = #$lang[$p1];
$cat2 = #$lang[$p2];
}
$postid = '';
$userid = '';
$pricemin = '';
$pricemax = '';
$location = '';
if(isset($_POST["filter"])){
$pricemin = $_POST["min"];
$pricemax = $_POST["max"];
$location = $_POST["location"];
}
main page code :
<div class="fp">
<div class="filter">
<b style="padding-left: 10px;">Filters:</b>
<form class="filterform" action="" method="post"><br>
Location: <br>
<input name="location" ><br>
Price Range:<br>
Min:<input type="text" name="min" size="5"> Max:<input type="text" name="max" size="5"><br><br>
<input class="submit-button" type="submit" name="filter" value="Filter">
</form>
</div>
<div class="posts">
<div id="adcat"><?php
if(!empty($cat2)){
?>
<a href="cat.php?catid=<?php echo $l1; ?>" ><?php echo $cat1." ยป "; ?></a><span><?php echo $cat2; ?></span>
<?php
} else {
echo "<font color='grey'>".$cat1."</font>";
}
?>
</div><br><br>
<div id="detailformscat">
<?php
if(empty($p1) && empty($p2)){
$sql = "SELECT * FROM posts p JOIN images i ON p.id = i.postid ";
if(!empty($location)){
$sql .= "AND location='$location'";
}
if(!empty($min)){
$sql.= "AND price>='$min' ";
}
if(!empty($max)){
$sql.= "AND price<='$max' ";
}
} else if(!empty($p2)){
$sql = "SELECT * FROM posts p JOIN images i ON p.id = i.postid WHERE catid='$p2' ";
if(!empty($location)){
$sql .= "AND location='$location'";
}
if(!empty($min)){
$sql.= "AND price>='$min' ";
}
if(!empty($max)){
$sql.= "AND price<='$max' ";
}
} else {
$sql = "SELECT * FROM posts p JOIN images i ON p.id = i.postid WHERE p.catid LIKE '$p1%' ";
if(!empty($location)){
$sql .= "AND location='$location'";
}
if(!empty($min)){
$sql.= "AND price>='$min' ";
}
if(!empty($max)){
$sql.= "AND price<='$max' ";
}
}
$res = mysqli_query($connect,$sql);
while ($row = mysqli_fetch_assoc($res)) {
$postid = $row["postid"];
?>
<div id="ads">
<div id="adfavcat">
<?php if(!isset($_SESSION["userid"])) { ?>
<?php } else {
$userid = $_SESSION["userid"];
$sql2 = "SELECT * FROM fav WHERE userid='$userid' AND postid='$postid' ";
$res2 = mysqli_query($connect,$sql2);
$rowcount = mysqli_num_rows($res2);
if ($rowcount > 0){ ?>
<?php
} else { ?>
<?php }
} ?>
</div>
<div id="titlepic">
<?php echo $row["title"]; ?><br>
<img src="<?php if(!empty($row["path1"])) { echo $row["path1"]; } else echo "image/noimage.png"; ?>" height="100px" width="150px">
</div>
<div id="datescat">
<b>Date Added:</b> <?php echo date('m/d/Y H:i', $row["dateadded"]); ?><br>
<b>Renew Date:</b> <?php if($row["renewdate"] > 0){ echo date('m/d/Y H:i', $row["renewdate"]); } ?><br>
<b>Location:</b> <?php echo $row["location"]; ?><br>
<b>Price:</b> <?php echo $row["price"]."£"; ?><br>
</div>
</div>
<hr width="100%">
<?php
}
?>
</div>
</div>
</div>
I think it's because you are treating the price as a string, in the sql query you wrote
$sql.= "AND price>='$min' ";
Try with cast/sanitize/filter input variables $min & $max to integers and removing the quotes.
--- by the way, I personally would also change some things:
use atom instead of brackets
use an ORM and remove the query from the html page (the view)
if 2 is not possible, try to move all php logic to the php file instead of the html part
remove all that IFs and try to write a code without lots of repetitions
You are also joining the tables instead of filtering, try changing
$sql = "SELECT * FROM posts p JOIN images i ON p.id = i.postid ";
with
$sql = "SELECT * FROM posts p JOIN images i ON p.id = i.postid WHERE p.id > 0 ";
change
$pricemin = '';
$pricemax = '';
with
$min = '';
$max = '';
My current program, for some reason, won't register my database values even though my previous code(looks identical but from different database tables) works just fine.
So far I have no errors when it runs. The only thing that prints for each page is the table's title. Also the clients page works just fine. So the product(tv, cell, computer) and transaction page are my current issue.
My current index.php file (main program) is as follows:
<?php
//url /index.php?action=clients
include('header.php'); // create top box
include('sidemenu.php'); // create side menu
//database connection
include('pdo_connect.php');
//Read data type
$type = "";
if (isset($_REQUEST['action']))
$type = $_REQUEST['action'];
//echo 'Action: {$type}';
switch($type) {
case 'products' : //display a list of clients
//define sql
$sql = "SELECT product_type, product_title, product_description, unit_price FROM products
WHERE product_type = :product_type";
$values = array(':product_type'=>$_GET['product_type']);
$products = getAll($sql);
//display result
displayProductList($products);
break;
case 'clients' : //displaya list of movies
$sql = "SELECT first_name, last_name, email FROM p_clients";
$clients = getAll($sql);
displayClientList($clients);
break;
case 'transactions' :
$sql = "SELECT products.product_title, products.product_description, products.unit_price, p_clients.first_name,
p_clients.last_name, sales.quantity FROM p_clients INNER JOIN sales, products ON p_clients.client_id = sales.client_id
AND products.product_id = sales.product_id";
$transactions = getAll($sql);
displayTransactionList($transactions);
break;
default:
defaultView();
break;
}
include('footer.php');
function defaultView() {
?>
<!-- add page content -->
<div id='content'>
<h2>Welcome to our movie store</h2>
</div>
<div id = 'image'></div>
<div id = 'box'>
<p id = 'text-box'>
We appreciate your interest in our products and services. Please reference
the the links provided to see our current specials for each of our clients.
</p>
</div>
<?php
}
function displayProductList($products) {
echo "<div id='content'>
<h2>List of Products</h2>";
echo "<table id = clients>";
echo "<tr><td id = 'title'>Product Name</td><td id= 'title'>Description</td><td id = 'title'>Cost</td></tr>";
//display each record
for ($i = 0; $i < count($products); $i++){
echo "<tr><td>{$products[$i]['product_title']} </td><td> {$products[$i]['product_description']} </td><td>
{$products[$i]['unit_price']} </td></tr>" ;
}
echo "</table>";
echo "</div>";
}
function displayClientList($clients) {
echo "<div id='content'>
<h2>List of Clients</h2>";
echo "<table id = 'long'>";
// echo "<table>";
echo "<tr><td id = 'title'>First Name</td><td id= 'title'>Last Name</td><td id = 'title'>Email</td></tr>";
//display each record
for ($i = 0; $i < count($clients); $i++){
echo "<tr><td>{$clients[$i]['first_name']}</td><td> {$clients[$i]['last_name']}
</td><td> {$clients[$i]['email']} </td></tr>";
}
echo "</table>";
echo "</div>";
}
function displayTransactionList($transactions) {
echo "<div id='content'>
<h2>List of Client Transactions</h2>";
echo "<table id = 'long'>";
// echo "<table>";
echo "<tr><td id = 'title'>First Name</td><td id= 'title'>Last Name</td><td id = 'title'>Product Title</td>
<td id = 'title'>Product Description</td><td id = 'title'>Cost</td><td id = 'title'>Quantity</td></tr>";
//display each record
for ($i = 0; $i < count($transactions); $i++){
echo "<tr><td>{$transactions[$i]['first_name']}</td><td> {$transactions[$i]['last_name']}
</td><td> {$transactions[$i]['product_title']} </td><td> {$transactions[$i]['product_description']} </td><td>
{$transactions[$i]['unit_price']} </td><td> {$transactions[$i]['quantity']} </td></tr>";
}
echo "</table>";
echo "</div>";
}
function getAll($sql, $values =null){
global $db;
$statm = $db->prepare($sql);
//Method 4
//assign a value to named parameters using an array
//$values= array(':genre'=>'drama');
$statm->execute($values);
//Fetch all records
$result = $statm->fetchAll();
return $result;
}
The sidemenu.php file calls each one from links:
<div id = 'sidebar'>
<h4>Links</h4>
<ul id = "nav" class= "text-left">
<li><a href='index.php'>Home</a></li>
<li><a href='index.php?action=products&product_type=tv'>TV Products</a></li>
<li><a href='index.php?action=products&product_type=cell'>Cell Phone Products</a></li>
<li><a href='index.php?action=products&product_type=computer'>Computer Products</a></li>
<li><a href='index.php?action=clients'>List of Customers</a></li>
<li><a href='index.php?action=transactions'>List of Transactions</a></li>
<!--<li><a href='index.php?action=moviesFS&genre=sci-fi&date_out=2009-12-15'>List of Favorite Sci-Fi Movies</a></li>-->
</ul>
</div>
As you can see, if I type my sql into my database it works just fine:
Try changing
$products = getAll($sql);
to
$products = getAll($sql,$values);
inside case 'products' :
I have a database with a few images already set, I would like to have the url display an ID from each query as the user hits next. The user should be able to share the URL and paste it into their browser, the url should pull that unique ID from the query. The issue i am having is every time i paste a url, I get a random image and not the image that is in the ID. I'm at a loss here and im not sure what to do :( here's the code I have so far.
<?php
if (isset($_GET['id'])) {
include("PHP/db.php");
echo $where = $_GET["id"];
echo $query = "SELECT * FROM images WHERE ID =" . $where;
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result);
$ID = $row['ID'];
$title = $row['name'];
$image = "<img height=500 width=600 src=http://www.goupics.com/img/" . $row['name'] . " >";
}
if($_GET['next4']) {
echo 'HELLO THIS IS THE NEXT IF METHOD';
include("PHP/db.php");
$query = "SELECT * FROM images ORDER BY RAND() LIMIT 1";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result);
$ID = $row['ID'];
$title = $row['name'];
$image = "<img height=500 width=600 src=http://www.goupics.com/img/" . $row['name'] . " >";
}
?>
<body>
</div>
<div id="title"> <?php echo $title ?> </div>
<div id="mainpic">
<?php echo $image ?>
</div>
<div id="prevnext">
<div id="next">
<a href="?id=<?php echo $ID ?>" name="name4" >Next</a>
</div>
<div id="prev">
Previous
</div>
</div>
Try this:
<?php
include("PHP/db.php");
$query2 = "SELECT * FROM images ORDER BY RAND() LIMIT 1";
$result2 = mysqli_query($dbc, $query2);
$rand_row = mysqli_fetch_array($result2);
$rand_id = $rand_row ['ID'];
if (!isset($_GET['id'])) {
$_GET['id'] = $rand_id;
}
if (isset($_GET['id'])) {
echo $where = $_GET["id"];
echo $query = "SELECT * FROM images WHERE ID =" . $where;
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result);
$ID = $row['ID'];
$title = $row['name'];
$image = "<img height=500 width=600 src=http://www.goupics.com/img/" . $row['name'] . " >";
}
?>
<body>
</div>
<div id="title"> <?php echo $title ?> </div>
<div id="mainpic">
<?php echo $image ?>
</div>
<div id="prevnext">
<div id="next">
<a href="?id=<?php echo $rand_id; ?>" name="name4" >Next</a>
</div>
<div id="prev">
Previous
</div>
</div>
I changed:
-link to next is now id=rand
-changed your code to give me a "rand ID" and its already defined on the href of the page you load
It will go inside condition (next == true).
Make sure that your variables are initialized before use.