Displaying same products with different images... PHP - php

I'm trying to make a website for people to post their cars for sale. I've done posting data into database. Everything works fine, but when they go to Member's page, it should show them added cars with photo, and edit button.
Here's my function to display added cars:
function get_user_auto($username) {
//extract from the database all the URLs this user has stored
$conn = db_connect();
$result = $conn->query("
SELECT
images.filename,
car_make.make,
car_model.model,
car_generation.name,
cars.year,
cars.price,
cars.car_id
FROM cars
LEFT JOIN car_make ON cars.make = car_make.make_id
LEFT JOIN car_model ON cars.model = car_model.model_id
LEFT JOIN car_generation ON cars.generation = car_generation.generation_id
LEFT JOIN images ON cars.car_id = images.car_id
WHERE cars.username = '$username';");
if (!$result) {
return false;
}
//create an array of the URLs
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$make = $row["make"];
$model = $row["model"];
$generation = $row["name"];
$year = $row["year"];
$price = $row["price"];
$filename = $row["filename"];
$imageURL = 'uploads/'.$filename;
?>
<img src="<?php echo $imageURL; ?>" alt="" width="100"/>
</div>
<div>
<?php echo "" . $make ." " . $model ." - " . $year ." " . $price ." USD";?>
Edit
</div>
</div>
<?php
}
} else {
echo "You did not add car for sale yet.";
}
}
So, i.e. I have added one car with 3 photos attached to it by car_id, when I retrieve data and echo it, it shows the same car 3 times with 3 different photos.

If you want only one row per car then you can add GROUP BY to query like this
GROUP BY car_id. This will allow only one row per car_id regardless of how many images car have (but it might not select image you like).

Related

SQL how to get all images to show for respective units

My question is how to get multiple images to display next to their respective units information. I am able to print out all the images below but unable to get each listing to print out its respective images. originally i was trying to do it as a single query but it was only printing out the same image multiple times so i tried to do two seperate queries but it did not work, how can i fix it?
// Define the query but only for info:
$querystats = 'SELECT 8052monticello.UNIT, 8052monticello.SIZE, 8052monticello.id, 8052monticello.PRICE';
$querystats.= ' FROM 8052monticello';
if ($r = mysqli_query($connection, $querystats)) { // Run the query.
// Retrieve and print every record:
while ($row = mysqli_fetch_assoc($r)) {
if ($row['PRICE']){
// echo "<img src='images/".$row['image_name']."' width='100'>";
print "<p><h3>{$row['UNIT']} Unit #</h3>
{$row['SIZE']} Sq Feet<br>
{$row['PRICE']} Monthly rent<br>
Edit
Delete
</p><hr>\n";
}
}
}
//get the images
$queryimage = 'SELECT photos.image_name, photos.fk_unit, 8052monticello.UNIT';
$queryimage.= ' FROM photos, 8052monticello';
$queryimage.= ' WHERE photos.fk_unit= 8052monticello.unit';
if ($r = mysqli_query($connection, $queryimage)) { // Run the query.
// Retrieve and print every record:
while ($row = mysqli_fetch_assoc($r)) {
if ($row['image_name']){
echo "<img src='images/".$row['image_name']."' width='100'>";
}
}
}
You can use a JOIN in your query to join both the monticello and photos table:
$query = '
SELECT
m.UNIT, m.SIZE, m.id, m.PRICE,
p.image_name
FROM 8052monticello m
INNER JOIN photos p ON p.fk_unit = m.unit';
Now you have access to $row['image_name'] in your loop.
while ($row = mysqli_fetch_assoc($r)) {
if ($row['PRICE']){
print "<img src=\"images/{$row['image_name']}\" width='100'>
<p><h3>{$row['UNIT']} Unit #</h3>
{$row['SIZE']} Sq Feet<br>
{$row['PRICE']} Monthly rent<br>
Edit
Delete
</p><hr>\n";
}
}
Updated: For each row, images are fetched from the database.
$query = "SELECT
m.UNIT, m.SIZE, m.id, m.PRICE
FROM 8052monticello m ";
$res = mysqli_query($connection, $query);
if (!$res){
// throw error here
}
$query2 = "SELECT p.image_name
FROM photos p
WHERE p.fk_unit = '%s' ";
while ($row = mysqli_fetch_assoc($res)) {
$res2 = mysqli_query($connection, sprintf($query2, $row["UNIT"]));
while($img = mysqli_fetch_assoc($res2)) {
echo "<img src=\"images/{$img['image_name']}\" width='100'>";
}
print "<p><h3>{$row['UNIT']} Unit #</h3>
{$row['SIZE']} Sq Feet<br>
{$row['PRICE']} Monthly rent<br>
Edit
Delete
</p><hr>\n";
}

Getting the value from ($_GET["Value"])

// PAGE ONE
This is the index page, Here I am printing out rows from a list of
movie´s with some basic info, title , year.
I am also adding edit and delete links to the movies,
these work by passing the row id's of that movie.
$sql = "SELECT c.* , d.* FROM category c , movies d WHERE c.ID=d.ID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<div class='floatbox collection'><table><tr><th>Titel</th><th>regissör</th><th>År</th><th>Genre</th><th>Ändra</th><th>Ta bort</th>";
while($row = $result->fetch_assoc()) {
echo
"<tr><td>".$row["title"]."</td><td>".$row["director"]."</td><td>"
.$row["year"]."</td><td>".$row["category"]."</td>
<td><a href='edit.php?row=".$row["ID"]."'>justera</a></td>
// delete link to send ID to next page
<td><a href='delete.php?delete=".$row["ID"]."'>stryk</a></td>";
}
echo "</table></div>";
} else {
echo "0 results";
}
// PAGE TWO
Here I have my $row[ID] trough $_get by the link on the previous page,
I have checked the value by "dumping" so I know that the row ID is in that
variable: The thing is, How do I call that $ID in my sql statement?
I'm trying to delete by calling that ID on the table row.
// Variable with correct ID value
if(isset($_GET["ID"]))
if($_GET["ID"]) = $ID; // This doesn't work, Do I need to convert
the $get_ID to a variable with the ID that can be called in the statement?
or is my syntax wrong?
// Delete join
$sql = "SELECT * FROM movies, category
INNER JOIN category ON movies.ID = category.ID
DELETE WHERE movies.ID = '$ID'"; // No syntax works here
// Any help appreciated.
// konfirmering
if ($conn->query($sql) === TRUE) {
echo "Register struket <br>
<a href='panel.php'>Gå tillbaka</a>";
} else {
echo "Fel vid anslutning : " . $conn->error;
}
As per your code your delete.php would be like this:
// Variable with correct ID value
if (isset($_GET["delete"])) {
$ID = $_GET["delete"];
// Delete join
$sql = "DELETE FROM movies, category INNER JOIN category ON movies.ID = category.ID WHERE movies.ID = '$ID'";
// konfirmering
if ($conn->query($sql) === TRUE) {
echo "Register struket <br><a href='panel.php'>Gå tillbaka</a>";
} else {
echo "Fel vid anslutning : " . $conn->error;
}
}

News comments count

I'm tired of searching for the solution my news comment system.
What i have.
I have 2 different mysql tables item (id, title, category_id, details) and comments (id, item_id, comment)
If i have single news then counting is fine like here in picture:
Single news
Code:
if (!empty($comments)) {
$comm = count($comments);
} else {
$comm = 0;
}
But if i use same code category view, result is:
Category view
If i use code:
$sqls = mysql_query("SELECT c.item_id,
COUNT(c.comment)
FROM comments c
RIGHT JOIN items i
ON c.item_id = i.id
GROUP BY c.item_id");
$comm = mysql_num_rows($sqls);
$smarty->assign('comm',$comm);
Result is :Some number of comments
How to make possible to see the Category View the correct number of comments?
TRY this example. The result is the same as the screenshot below but with some background colour to distinguish the difference. Of course you should change to your own connection and layout.
<?php
$db = new PDO('sqlite:news.db');//change to your own
$sql = $db->prepare("
SELECT item.id, item.title, item.details, comments.comment, COUNT(comments.id) AS NumberOfComment
FROM item LEFT JOIN comments ON item.id = comments.item_id
GROUP BY item.id ORDER BY item.id");
$sql->execute();
$row = $sql->fetchAll();
//get comment
$comment = $db->prepare("SELECT comment FROM comments WHERE item_id = ?");
foreach ($row as $rows){
echo "<br>";
echo "Title: ".$rows['title'];
echo "<br>";
echo "Details: ".$rows['details'];
echo "<br>";
echo "<i>".$rows['NumberOfComment']." comments </i>";
echo "<br>";
$comment->execute(array($rows['id']));
$comments = $comment->fetchAll();
echo '<div style="background-color:pink;">';
foreach ($comments as $showcomment){
echo $showcomment['comment'];
echo "<br>";
}
echo "</div>";
echo "<br>";
}
?>
example item table
example comment table
and the result is...

Sql Query: 2 tables but looking for all information from one and only one row from the other

I have 2 tables
Photos: stores all photo information
Gallery: stores heading and description about the gallery
I need to echo to a new page the Gallery Description, then all the photos that should be there.
but I keep getting heading and description repeating because its in the same
$row = mysql_fetch_array($result)...
then there is more that one set of photos in that gallery I need also?
anyone help or am I being to vague....
$a="SELECT * from gallery where gallery_category=".$gallery_category;
$result = mysql_query($a,$c);
while($row = mysql_fetch_array($result)) {
echo $row['gallery_name'].'<br>'.$row['gallery_description'].'<br>';
$sql="SELECT * FROM photos WHERE gallery_id =".$gallery_id." ORDER BY photos_filename";
$result2 = mysql_query($sql,$c);
while($row = mysql_fetch_array($result2)) {
echo'<a rel="example_group" href="../galleries/images/'.$row['gallery_id'].'/'.$row['photos_filename'].'" width="130" height="100"><img src="../galleries/images/'.$row['gallery_id'].'/'.$row['photos_filename'].'" height="150px" alt=""/></a>';
}
}
Actually I'll post it up here so I can use some code formatting.
Option 1 - loop within a loop
$headerquery = $db->query("SELECT * FROM tbl1");
while ($headers= $db->fetchNextObject($headerquery )) {
echo "<table><tr><th>".$headers->GalleryName."</th></tr>"; // open table create header
$detailquery = $db->query("SELECT * FROM tbl2 WHERE GalleryID=".$headers->ID);
while ($details= $db->fetchNextObject($detailquery )) {
echo "<tr><td>".$details->Photo."</td></tr>"; //loop through 2nd table and spit out photos
}
echo "</table>"; //close table
}
Option 2 - joined query with selector
$galleryheaderid = 0;
$query = $db->query("SELECT * FROM tbl1 INNER JOIN tbl2 on tbl1.ID=tbl2.GalleryID");
while ($details = $db->fetchNextObject($query )) {
echo "<table>";
if ($galleryheaderid!=$details->ID) { //spit out header row if id's don't match
echo "<tr><th>".$details ->GalleryName."</th></tr>"; //create header
$galleryheaderid = $details->ID; //set header id to gallery id so we don't show header a 2nd time
}
echo "<tr><td>".$details->Photo."</td></tr>"; //spit out gallery information even on first row since all rows include photo information
echo "</table>"; //close table
}
Something like either of these should work obviously they'll need completing properly

PHP/MySQL Query Results

Having an issue with a query..my wscategories stores the main categories of an online store, and my wssubcategories table stores the sub categories of the table with the foreign key called "parentcategory". I'm trying to list the main categories, with the subcategories underneath a la:
Tops
T-Shirts
Wovens
Sweaters
Pants
Shorts
Jeans
The query/result I wrote is the following:
$query = "SELECT DISTINCT a.categoryname AS maincategory, b.categoryname AS
smallcategory FROM wscategories a, wssubcategories b WHERE a.SECTION = 'girls' AND
b.parentcategory = a.id";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo $row['maincategory'];
echo "<br/>";
echo $row['smallcategory'];
echo "<br/>";
}
Which returns:
Tops
T-Shirts
Tops
Sweaters
Tops
Wovens
Etc. I want the script to just display the main category once, and then the subcategories underneath vs. displaying it multiple times. Any help?
try something like this
// note we need to order by maincategory for this to work
//
$query = "SELECT DISTINCT a.categoryname AS maincategory, b.categoryname AS
smallcategory FROM wscategories a, wssubcategories b WHERE a.SECTION = 'girls' AND
b.parentcategory = a.id
ORDER BY maincategory ASC,
smallcategory ASC
";
$result = mysql_query($query) or die(mysql_error());
// keep track of previous maincategory
$previous_maincategory = NULL;
while ($row = mysql_fetch_assoc($result))
{
// if maincategory has changed from previouscategory then display it
if ($previous_maincategory != $row['maincategory']) {
echo $row['maincategory'];
}
echo "<br/>";
echo $row['smallcategory'];
echo "<br/>";
// record what the previous category was
$previous_maincategory = $row['maincategory'];
}
Set a flag after you echo the main category, like this:
$echoed_main = false;
while ($row = mysql_fetch_array($result)) {
if (!$echoed_main) {
echo $row['maincategory'];
echo "<br/>";
$echoed_main = true;
}
echo $row['smallcategory'];
echo "<br/>";
}

Categories