Selecting one image out of 5 images for one item - php

I have tried to create a script that loops through 5 items that match 1 item and then show one image associated with each of the 5 items.
Here is a fiddle I create to illustrate my issue.
http://sqlfiddle.com/#!2/17d66/1/0
I want to select one picture from each matching item. Here is the code I have come up with but so far it is not working. There are two points of comparison I have used, a tag and family. The tag associated with the type of product and the family is the category it belongs to. For instance, the iPhone 4 would have smartphone for a tag and iPhone 4 as the family. Any help would be appreciated, my code is below.
<?php
// main product
$images = "SELECT img_id FROM product_images WHERE img_tag = '$p_type' && img_family = '$p_family' LIMIT 5";
$img_list = mysql_query($images);
while($rows = mysql_fetch_array($img_list)) {
$img_name = $rows['img_name'];
$img_tag = $rows['img_tag'];
$img_family = $rows['img_family'];
$img_id = $rows['img_id'];
//echo $img_name;
<div>
<img src="view.php?h=400&w=400&imgid=<?php echo $img_id; ?>" />
</div>
}
</div>
</div>
<div id="left_other">
<div class="titleHeaders">Other matching items:</div>
<?php
$match_items = "SELECT id,product_name,product_type FROM product_list WHERE name_family = '$p_family' AND id <> '$id' LIMIT 5";
$match_q = mysql_query($match_items);
$count = mysql_num_rows($match_q);
if($count > 0) {
//get matching products
while($items = mysql_fetch_array($match_q)) {
$id = ($items['id']);
echo "<p>$id</p>";
$p_name = ($items['product_name']);
echo "<p>$p_name</p>";
$type = ($items['product_type']);
echo "<p>$type</p>";
$full = "$p_name $type";
echo "<p>$full</p>";
//get photos
$other_photos = "SELECT * FROM product_images WHERE img_family = '$p_family' AND img_tag <> '$p_type' LIMIT 1";
echo $other_photos;
$other_q = mysql_query($other_photos);
while($pictures = mysql_fetch_array($other_q)) {
echo "<p>----------------------</p>";
$theid = ($pictures['img_id']);
echo "<p>$theid</p>";
$photo = ($pictures['img_name']);
echo "<p>$photo</p>";
$thetype = ($pictures['img_tag']);
echo "<p>$thetype</p>";
echo "<p>----------------------</p>";
if($photo != $newname && $theid != $newid){
if ($photo == '') {
$poly = 'images/pph.jpg';
//echo $poly;
}else{
$poly = 'product_images/regular_images/'.$photo;
//echo $poly;
} // end if
$newname = $photo;
$newid = $theid;
}else{
echo "<p>The photo name is the same!</p>";
}

You can use a single query to grab the results. Here is how you can do it.
SELECT
pl.id,
pl.product_name,
pl.product_type ,
pi.product_images
FROM product_list AS pl
LEFT JOIN (SELECT product_list_id , product_images FROM product_images LIMIT 1) AS `pi` ON pi.product_list_id = pl.id
WHERE pl.img_tag = '$p_type' AND pl.img_family = '$p_family'
LIMIT 5
But it would be batter if there was some table structure , sample data and desired output.
EDIT
Try this query and you can put a where at last
SELECT
*
FROM
`products` AS p
LEFT JOIN (SELECT MAX(img_id), img_name, img_tag, img_family FROM `images`) AS i ON i.img_family = p.`p_family` AND i.img_tag = p.`p_tag` ;
EDIT
SELECT *
FROM `products` AS p
LEFT JOIN images as i
ON i.img_family = p.`p_family`
group by p.p_name;

Related

PHP and MySQL: How to get all database entries form two tables?

I have the following code which gets data from a table entry and displays some html for each entry. It works fine but i want it to display html for the entries in that table AND another table. I could just duplicate this code and change it a bit to get the entries in a different table but that creates another problem, all the entries from the second table would start at the end of the entree list from the first table. How can I display the entries from both table in the order of most relevant to what the user types in? Here is my code that just displays entries from the first table in order of when they were inserted into the table. Can someone tell me how to display all the entries from two different tables in order of relavace to a user search query? My code so far, I have not been able to get much further than this.
$pagesQuery = mysql_query("SELECT count(id) FROM(`posts`) WHERE `title` LIKE '%{$terms}%' OR `descrip` LIKE '%{$terms}%'");
$pageNum = ceil(mysql_result($pagesQuery, 0)/5);
$start = (($page-1)*5);
$currentname = mysql_query("SELECT * FROM `posts` WHERE `title` LIKE '%{$terms}%' OR `descrip` LIKE '%{$terms}%' LIMIT $start, 5");
while ($row = mysql_fetch_array($currentname)) {
//recieve relevant data.
$title = $row[0];
$desc = $row[13];
$ID = $row[6];
$views = $row[3];
$user = $row[7];
$type = $row[15];
//fetch the last id from accounts table.
$fetchlast1 = mysql_query("SELECT * FROM allaccounts WHERE id=(SELECT MAX(id) FROM allaccounts)");
$lastrow1 = mysql_fetch_row($fetchlast1);
$lastid1 = $lastrow1[6];
//acquire the username of postee.
for ($i1=1; $i1 <= $lastid1; $i1++) {
$currentname1 = mysql_query("SELECT * FROM allaccounts WHERE id=$user");
while ($row1 = mysql_fetch_array($currentname1)) {
$username1 = $row1[0];
}
}
//Format Title, description and view count.
$title2 = rtrim($title);
$donetitle = str_replace(" ", "-", $title2);
$donetitle1 = str_replace(".", "", $donetitle);
$donetitle2 = str_replace("-", "-", $donetitle1);
$donetitle3 = str_replace(":", "-", $donetitle2);
$url = "articles/".$ID."/".$donetitle3."";
$donetitle = strlen($title) > 40 ? substr($title,0,40)."..." : $title;
$donedesc = '';
if(strlen($desc) > 150) {
$donedesc = explode( "\n", wordwrap( $desc, 150));
$donedesc1 = $donedesc[0] . '...';
} else {
$donedesc1 = $desc;
}
$SRCIMG = '';
$finviews = number_format($views, 0, '.', ',');
if($type == '1'){
$SRCIMG = "img/icons/video.png";
} else {
$SRCIMG = "img/icons/article.png";
}
//Give results
if($row[10] == null){
$SRC = "img/tempsmall.jpg";
}else{
$SRC ="generateThumbnailSmall.php?id=$ID";
}
echo "<div id = \"feature\">
<img src=\"$SRC\" alt = \"article thumbnail\" />
<img src=\"$SRCIMG\" alt = \"icon\" id=\"icondisp\"/>
</div>
<div id = \"feature2\">
$donetitle
<p id=\"resultuser\" >$username1</p>
<p id=\"resultp\">$donedesc1</p>
<img src=\"img/icons/flag.png\"/><b id=\"resultview\">$finviews views</b>
</div>
<div id = \"border\"></div>";
}
In this case you ought to use UNION to merge SELECT results from two or more tables.
So you query should look like this:
(SELECT *
FROM `posts`
WHERE `title` LIKE '%{$terms}%'
OR `descrip` LIKE '%{$terms}%')
UNION
(SELECT *
FROM `posts2`
WHERE `title` LIKE '%{$terms}%'
OR `descrip` LIKE '%{$terms}%')
LIMIT $start, 5
Notice that number and names of columns in both SELECTS should be the same.
Why not try union ?
SELECT * FROM `posts` WHERE `title` LIKE '%{$terms}%' OR `descrip` LIKE '% {$terms}%'
union
SELECT * FROM `otherposts table` WHERE `title` LIKE '%{$terms}%' OR `descrip` LIKE '%{$terms}%'
order by yourRelevanceField
LIMIT $start, 5"
Actually it just hit me, I should probably create a new table called SearchElements where I store data needed for a search result. I would create a SearchElement each time an entree is added to either table. still dont understand relevance yet though.
Well you can go for UNION of two tables and try something like this
INSERT INTO table3
SELECT * FROM tabel1
UNION
SELECT * FROM tabel2

How can i check sql , and use something like do case

I am listing the categories and when clicking category it has to show if there is subcategory . If there isnt subcategory it includes products and have to list products. I mean if includes product case b, else case a
I can use query a or b, But i dont know how to check if have products so use query a else use query b.
Sql :
Categories : id | parent_id | name
product to category : id | product_id | category_id
query a (category list):
<?php
$query_product = mysql_query("SELECT * FROM categories WHERE status = '1' AND parent_id = '".$row['id']."' ORDER BY sort_order");
while($row_product = mysql_fetch_array($query_product)){
$product_name = $row_product['name'];
}
?>
query b (product list):
$query_product_id = mysql_query("SELECT * FROM product_to_category WHERE category_id = '".$row['id']."'");
while($row_product_id = mysql_fetch_array($query_product_id)){
//sort order yapilacak.
$query_product = mysql_query("SELECT * FROM products WHERE status = '1' AND id = '".$row_product_id['product_id']."' ORDER BY sort_order");
$row_product = mysql_fetch_array($query_product);
$product_name = $row_product['name'];
}
?>
Sorry for not telling my question clearly.I found a solution like this but couldnt integrate. I can check if there are products.
I have to use a variable like $code includes
<div id="container-portfolio" class="portfolio-4">
<?php
$query_product = mysql_query("SELECT * FROM categories WHERE status = '1' AND parent_id = '".$row['id']."' ORDER BY sort_order");
while($row_product = mysql_fetch_array($query_product)){
if($language != 'TR'){
$query_product_lang = mysql_query("SELECT image FROM categories WHERE language = '".$language."' AND language_parent_id = '".$row_product['id']."'");
$row_product_lang = mysql_fetch_array($query_product_lang);
$product_name = $row_product_lang['name'];
} else {
$product_name = $row_product['name'];
}
?>
and $link
<a href="<?php echo get('site_link'); ?>c/<?php echo $row_product['link']; ?>" >
<img src="<?php echo HTTP_RESIM.'categories/'.$row_product['image']; ?>" alt="" /></a>
Then use the if statement like below. If you can help me for editing variables, i could use the others i think. Getting errors converting html to php for echo code.
Regards
<?php $sql = mysql_query("SELECT * FROM product_to_category WHERE category_id = '".$row['id']."'");
$urun = mysql_num_rows($sql);
if($urun > 0) {
$code= "......";
$link= "....";
} else {
$code= "......";
$link= "....";
}
?>

trying to form SQL join on several tables

So Im trying to figure out how to do this with 1 query if possible. Here is what I have with several queries
$file_url = 'http://'.$cms.'/filemanager/gallery';
$link_url = '/our-process/gallery/';
include 'inc/config.php';
function gallerySafeName($var){
$var = strtolower(preg_replace('([^a-zA-Z0-9_])','-',$var));
return $var;
}
$galleryimages = array();
$sql = "SELECT * FROM `cms_gallery_categories` ORDER BY RAND() LIMIT 3";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)){
$sql1 = "SELECT * FROM `cms_gallery_images` WHERE `image_id` = ".$row['category_image_id'];
$result1 = mysqli_query($con,$sql1);
while ($row1 = mysqli_fetch_array($result1)){
$sql2 = "SELECT * FROM `cms_gallery` WHERE `gallery_id` = ".$row1['gallery_id'];
$result2 = mysqli_query($con,$sql2);
while ($row2 = mysqli_fetch_array($result2)){
print '<li>
<a href="'.$link_url.$row['category_name'].'/'.$row2['gallery_name'].'/'.gallerySafeName($row1['image_caption']).'/">
<img width="210" height="133" border="0" src="'.$file_url.'/'.$row['category_name'].'/'.$row2['gallery_name'].'/'.$row1['image_name'].'" />
</a>
</li>';
}
}
}
Im trying to get 3 random entries from the gallery category and the image assigned to represent that category. Then get the gallery name and then the image name to form a img src and link. My table structure is as follows
-cms_gallery_categories
category_id
category_title
category_name
category_image_id
-cms_gallery
gallery_id
gallery_title
gallery_name
category_id
-cms_gallery_images
image_id
image_name
image_caption
gallery_id
Images belong to galleries, and galleries belong to categories
SELECT GC.*, G.*, I.*
FROM cms_gallery_categories GC
INNER JOIN cms_galleries G ON (G.category_id = GC.category_id)
INNER JOIN cms_gallery_images I ON (I.gallery_id = G.gallery_id)
ORDER BY RAND() LIMIT 3
You will want to limit your fields to what you need only. From what I can see in your code, it's this:
SELECT GC.category_name, G.gallery_name, I.image_caption FROM...
More info
http://www.w3schools.com/sql/sql_join.asp
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
http://www.tutorialspoint.com/sql/sql-using-joins.htm

Pagination. Select from x number of tables

i'm trying to make my second website using php and i'm stuck at some typical problem (i believe),
but very hard for me.
I'm making a page that show list of items depends on GET.
#1 if only "type" sended - show all items with x type.
#2 if only "tag" sended - show all items with x tag.
#3 if "type" and "tag" sended at the same time - show all items with x type and x tag.
problem #1 i solved this way
// items per page
$per_page = 5;
// 1) if isset type
if ( (isset($_GET['type'])) && (!isset($_GET['tag'])) ){
$type_id = get_safe_var($_GET['type']);
$con = mysql_connect(DB_HOST,DB_LOGIN,DB_PASSWORD) or die(mysql_error());
if ($con) {
mysql_select_db(DB_NAME) or die(mysql_error());
$sql = mysql_query("SELECT `item_type`, `item_type_name` FROM `item_types` WHERE `type_id` = '$type_id'");
$row = mysql_fetch_assoc($sql);
$type = $row['item_type'];
$type_name = $row['item_type_name'];
if ($type != ''){
$pages_query = mysql_query("SELECT COUNT(`id`) FROM `".$type."` WHERE `insearch` = '1'");
$number_of_pages = ceil( mysql_result($pages_query, 0) / $per_page );
$current_page = ( (isset($_GET['page'])) && ((int)$_GET['page'] > 0) ) ? (int)$_GET['page'] : 1;
$start = ($current_page - 1) * $per_page;
echo "<h1>$type_name</h1>";
$sql = mysql_query("SELECT `id`, `name`, `img` FROM `".$type."` WHERE `insearch` = '1' ORDER BY `id` DESC LIMIT $start, $per_page");
// echo items
while ($row = mysql_fetch_assoc($sql)){
$id = $row['id'];
$name = $row['name'];
$img = $row['img'];
echo "
<div id='items_cell'>
<img alt='$name' src='$img' width='145' height='200' /><br />
<a href='open_item.php?type=$type_id&id=$id'>$name</a><br />
<em>$type_name</em>
</div>";
}
}
mysql_close($con);
} else {echo 'sql connection error';}
}
pagination
// echo pagination
// 1) if isset type
if ( (isset($_GET['type'])) && (!isset($_GET['tag'])) ){
if ( (isset($number_of_pages)) && ($number_of_pages >= 1) && ($current_page <= $number_of_pages) ){
for ($i = 1; $i <= $number_of_pages; $i++){
if ($i == $current_page){
echo "<li><a href='?type=$type_id&page=$i' class='sel'>$i</a></li>";
} else {
echo "<li><a href='?type=$type_id&page=$i'>$i</a></li>";
}
}
}
}
I'm stuck at problem #2.
I got tag ID. Need to show all items with that tag.
I don't understand how to make a SELECT from x-number of tables with a working paginatin.
database structure -
Any help is welcome!
P.S. Maybe i need to change db structure to make SELECT easier?
You should definitely work on your table design. Having dynamic table names is a big NO-NO as you won't ever be able to do any useful joins. Just create one big tag-table and add a column type like you did in your table item_types.
To solve problems #1-#3 just build the WHERE-part of your query dynamically:
// empty selection
$where = array();
if (!empty($_GET["type"])
$where[] = "`item_type` = '".mysql_real_escape_string($_GET["type"])."'";
if (!empty($_GET["tag"])
$where[] = "`tag` = '".mysql_real_escape_string($_GET["tag"])."'";
$query = "SELECT ... FROM `item`"
// Join type-table
. " JOIN `item_types` ON `item`.`id` = `item_types`.`item_id`"
// Join all of this item's tags
. " JOIN `item_tags` ON `item`.`id` = `item_tags`.`item_id`"
// Filter tags by item_type
. " AND `item_types`.`item_type` = `item_tags`.`item_type`"
;
if (count($where) > 0)
$query .= "WHERE ".implode(" AND ", $where);

Running two queries for each individual thing

Sorry about the lame title, but I really don't know how to explain it!
Basically, I want to query the game categories from a table, then query games from another table which equal the category of the category queried from the categories table.
Got me so far?
This is the code I have so far...
$get_categories_query = mysql_query("
SELECT *
FROM game_categories
ORDER BY category_name ASC");
while ($row = mysql_fetch_array($get_categories_query)) {
$category_name = $row['category_name'];
$get_category_games = mysql_query("
SELECT *
FROM games
WHERE category = '$category_name'
ORDER BY RAND() LIMIT 5");
while ($row = mysql_fetch_array($get_category_games)) {
$category_game_id = $row['id'];
$category_game_title = $row['game_title'];
$category_game_display .= '<li><img
class="category_module_img"
src="http://www.game.assets.buddyweb.me/' .
$category_game_id .
'/_thumb_100x100.png"></li>';
}
$category_display .= '<div class = "category_module">
<h4>'.$category_name.'</h4>
'.$category_game_display.'
<div class="play_more_btn">More</div>
</div>';
}
But what I get from that is every game appearing from the query from the first category in the list.
I think the problem is the $row variable.
Try this:
$get_categories_query = mysql_query("SELECT * FROM game_categories ORDER BY category_name ASC");
while($row = mysql_fetch_array($get_categories_query))
{
$category_name = $row['category_name'];
$get_category_games = mysql_query("SELECT * FROM games WHERE category = '$category_name' ORDER BY RAND() LIMIT 5");
$category_game_display = false; // new!!
while($row_cat = mysql_fetch_array($get_category_games))
{
$category_game_id = $row_cat['id'];
$category_game_title = $row_cat['game_title'];
$category_game_display .= '<li><img class = "category_module_img" src = "http://www.game.assets.buddyweb.me/'.$category_game_id.'/_thumb_100x100.png"></li>';
}
$category_display .= '<div class = "category_module"><h4>'.$category_name.'</h4>'.$category_game_display.'<div class = "play_more_btn">More</div></div>';
}

Categories