Sql search from 2 or 3 table - php

I have a search form where I can search for my webshop products.
1 product can be in multiple categoris, not just in one. I store this in the termek_katgoria_kapcsolo table. At insert, it creates as many lines, as the product belong to many categoria.
Example: The ID 12 product belong to ID 1, ID 2, ID 3 categoria.
The search sql only look at categoria, when one categoria is selected. Most often, I just search for the products name, I don't sort it to categoris.
How can I write the sql, that if I select a categoria also? I show you the tables on a pic.
if($termek_kategoria == 0 ) // Sort to categoria or not only search for product name, id...
{
$sql = "
SELECT termek_id, termek_nev, termek_cikkszam, termek_status FROM termek
WHERE $kereses_helye LIKE '%$kw%' ORDER BY $kereses_rendezes $kereses_sorrend
";
}
else
{
// Sorting for categoria also
$sql = "
SELECT termek_id, termek_nev, termek_cikkszam, termek_status FROM termek
WHERE $kereses_helye LIKE '%$kw%' AND termek_kategoria =
'$termek_kategoria' ORDER BY $kereses_rendezes $kereses_sorrend
";
}
Update:
$sql = "
SELECT termek.termek_id, termek.termek_nev, termek.termek_cikkszam, termek.termek_status
termek_kategoria_kapcsolo.*, termek_kategoria.kat_id
FROM termek
LEFT JOIN termek_katgoria_kapcsolo ON termek_kategoria
WHERE termek_kategoria_kapcsolo.kat_kapcs_kategoria_id = termek_kategoria.kat_id
AND termek.termek_id IN (SELECT kat_kapcs_termek_id FROM
termek_kategoria_kapcsolo WHERE kat_kapcs_kategoria_id = '$termek_kategoria')
";
This result:
Whats going wrong here?
What I want is when I select a categoria, the program give me the products, that are in the selected categoria.

I solved the problem:
$sql =
"
SELECT
t.termek_id,
t.termek_nev,
t.termek_cikkszam,
t.termek_status,
kapcs.kat_kapcs_kategoria_id,
kapcs.kat_kapcs_termek_id
FROM termek t
LEFT JOIN termek_katgoria_kapcsolo kapcs ON kapcs.kat_kapcs_kategoria_id = '$termek_kategoria'
WHERE t.termek_id = kapcs.kat_kapcs_termek_id AND t.$kereses_helye LIKE '%$kw%' ORDER BY t.$kereses_rendezes $kereses_sorrend
";

Related

Select a fixed number of records from a particular user in a sql result

I have 2 tables - users and articles.
users:
user_id (int)
name (varchar)
articles:
article_id (int)
user_id (int)
title (varchar)
description (text)
In my application I need to display 20 RANDOM articles on a page.
My query is like this:
SELECT a.title
, a.description
, u.name
FROM articles a
JOIN users u
USING (user_id)
ORDER
BY RAND()
LIMIT 20
A user can have any number of articles in the database.
Now the problem is sometimes out of 20 results, there are like 9-10 articles from one single user.
I want those 20 records on the page to not contain more than 3 (or say 4) articles from a particular user.
Can I achieve this through SQL query. I am using PHP and MySQL.
Thanks for your help.
You could try this?
SELECT * FROM
(
SELECT B.* FROM
(
SELECT A.*, ROW_NUMBER() OVER (PARTITION BY A.USER_ID ORDER BY A.R) USER_ROW_NUMBER
FROM
(
SELECT a.title, a.description, u.name, RND() r FROM articles a
INNER JOIN users u USING (user_id)
) A
) B
WHERE B.USER_ROW_NUMBER<=4
) C
ORDER BY RAND() LIMIT 20
Mmm, intresting I don't think this is possible through a pure sql query.
My best idea would be to have an array of the articles that you'll eventually display query the database and use the standard SELECT * FROM Articles ORDER BY RAND() LIMIT 20
The go through them, making sure that you have indeed got 20 articles and no one has breached the rules of 3/4 per user.
Have another array of users to exclude, perhaps using their user id as an index and value of a count.
As you go through add them to your final array, if you find any user that hits you rule add them to the array.
Keep running the random query, excluding users and articles until you hit your desired amount.
Let me try some code (it's been a while since I did php)
$finalArray = [];
$userArray = [];
while(count($finalArray) < 20) {
$query = "SELECT * FROM Articles ";
if(count($finalArray) > 0) {
$query = $query . " WHERE articleID NOT IN(".$finalArray.")";
$query = $query . " AND userID NOT IN (".$userArray.filter(>4).")";
}
$query = $query . " ORDER BY Rand()";
$result = mysql_query($query);
foreach($row = mysql_fetch_array($result)) {
if(in_array($finalArray,$row) == false) {
$finalArray[] = $row;
}
if(in_array($userArray,$row[userId]) == false) {
$userArray[$row[userId]] = 1;
}
else {
$userArray[$row[userId]] = $userArray[$row[userId]] + 1;
}
}

Excluding certain unique IDs and then grouping the remaining ones

So I'm building a car booking website. And there is a cars tables that is like this:
Cars
CarID
CarModel
CarMake
Registration
And also a reservations table like this:
Reservations:
ReservationID
CarID
StartDate
EndDate
So When a user inputs the dates which they would like to book a car I query my reservations table:
If the dates are already in the reservation table I want to get that car ID, and then exclude that car from the list the user is shown, so they can not book it.
My problem is that I have multiple cars in the Database that are the same mode and make but have a different CarID and Registration.
I also group the cars by model so that a user is only shown one car of a certain type.
$carstring = mysql_query("SELECT * FROM cars {$statement} AND deleted = 'no'" GROUP BY CarModel);
$getcars = $carstring;
while($searchcars = mysql_fetch_array($getcars)) {
$checkreservations = mysql_query("SELECT * FROM reservations WHERE startDate = '".$sqlcoldate."' and carID = '".$searchcars['carID']."'");
$thiscar_num_rows = mysql_num_rows($checkreservations);
So as you can see at the minute I can tell which cars are taken in the reservations table, and I can echo out true or false from the num_rows
However I think it is the wrong way around because what I want to do is find out which cars by CarID are already taken, and then exclude them from the $getcars query loop that displays all the cars to the user, then group by model.
Can anyone tell me a way to do this, or even a better way to go about it?
An easy way to exclude the cars that are reserved is awith a subquery that gets all cars that ARE reserved and than stating in the main query that those cars are not allowed with the CarID NOT IN construction
<?php
// select all cars that are not reserved at sqlcoldate
$sql = "SELECT *
FROM Cars
WHERE CarID NOT IN (
SELECT CarID
FROM Reservations
WHERE StartDate > '".$sqlcoldate."' and EndDate < '".$sqlcoldate."'
)
GROUP BY CarModel";
// execute that query
$result = mysql_query($sql);
// if there are no results print a message
if (mysql_num_rows($result) == 0) {
echo "No cars found";
exit; // Exit the function, because there is nothing to do
}
// else print all available cars
while ($row = mysql_fetch_assoc($result)) {
echo "Model available car is :" . $row["CarModel"] . " </br>";
}
?>
Didn't actualy test it. But it should work
SELECT c.* FROM cars c
LEFT JOIN reservations r
ON c.carID=r.carID AND
selected_date BETWEEN r.startDate AND r.endDate
WHERE r.carID is null

mysql: group results, limit them and join to other tables in one query

i have a online application for wich i require a sort of dashboard (to use the white-space).
There are three tables used for the operation:
1.) categories: id, name
2.) entries: id, name, description, category_id, created, modified
3.) entryimages: id, filename, description, entry_id
on the dashboard i want to show 4-5 entries (with thumbnail images, so i require joins to the entryimages table and the categories table) for each category.
I read through some articles (and threads on s.o.) like this one:
http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/
But am still not getting it right, i've tried to first extract all categories and for each and every category build a query and with "all union" attach them to one, but that is not working.
The last version of code i used:
foreach($categories as $id => $name)
{
$query .= "SELECT `entry`.`id`,
`entry`.`name`,
`entry`.`description`,
`entry`.`category_id`,
`entry`.`created`,
`entry`.`modified`,
`entryimages`.`filename`,
`entryimages`.`description`
FROM `entries` as `entry` LEFT JOIN `entryimages` ON `entryimages`.`entry_id` = `entry`.`id`
WHERE `entry`.`category_id` = $id ";
if($i < count($groups))
{
$query .= 'UNION ALL ';
}
$i++;
}
$result = mysql_query($query);
Does anybody know what is the best right to accomplish this operation?
Thanks 1000
On the dashboard if you want to show three entries, the way you are doing is wrong. If my understanding is right, the entire query will be something like
"SELECT `entry`.`id`,
`entry`.`name`,
`entry`.`description`,
`entry`.`category_id`,
`entry`.`created`,
`entry`.`modified`,
`entryimages`.`filename`,
`entryimages`.`description`
FROM `entries` as `entry`
INNER JOIN categories
ON (entry.category_id = categories.id)
LEFT JOIN (SELECT * FROM `entryimages` WHERE `entry_id` = `entry`.`id` LIMIT 1) AS `entryimages`
ON `entryimages`.`entry_id` =`entry`.`id`
ORDER BY `entry`.`created` DESC LIMIT 5";
Your code looks ok to me you should just add a LIMIT clause so that you get just five of them and an ORDER BY clause to get the latest
$query .= "SELECT `entry`.`id`,
`entry`.`name`,
`entry`.`description`,
`entry`.`category_id`,
`entry`.`created`,
`entry`.`modified`,
`entryimages`.`filename`,
`entryimages`.`description`
FROM `entries` as `entry` LEFT JOIN `entryimages` ON `entryimages`.`entry_id` = `entry`.`id`
WHERE `entry`.`category_id` = $id ORDER BY `entry`.`created` DESC LIMIT 5";

How to show how many people wants a product in mySQL?

I have the following query
$query2 = "SELECT reverse_products.id, reverse_products.name, reverse_relations.user_id
FROM reverse_products JOIN reverse_relations ON reverse_products.id = reverse_relations.product_id
WHERE product_id = $dealid ";
$row = mysql_fetch_array(mysql_query($query2));
echo "$row[id]: $row[name]";
that shows the id and name of a product from reverse_products table. On the reverse_relations table there are stored *user_id* and *product_id*. There are many *user_id* that may have the same *product_id*.
How to change my query to show :
On how many *user_id* have the same *product_id* ? Do I need a second query for this ?
SELECT count(user_id)
FROM reverse_relations
GROUP BY product_id
WHERE product_id = $dealid
if I'm understanding your table structure properly.
count(reverse_relations.user_id) as num
echo $row[num]

How to combine result sets of a sql query?

I am having 5 checkbox with the food items like Chicken, fruits, vegetables, Snacks,.. like that.
What i am trying to implement is when the user selects the checkbox items and clicks submit, it will search for the restaurants providing the selected items,
Table will have 2 fields: restid, menu and the data is stored like this in the table
restid->1, menu->chicken
restid->1, menu->Burger
restid->2, menu->fruits
restid->3, menu->chicken
My doubt is how to search for the restaurants in the table. My plan is, loop through the for loop for each item with the select statement like (select * from restaurant_table where menu='menu';)
when we loop through the loop how can we combine the results for each menu?
Plz help any help will be appreciated
i hope you are having two table restaurant and menu
restaurant - restid, name
menu - menuid, restid, menu
the php code can be like this
<?php
//$_POST['menus'] is the array of checkboxes
foreach($_POST['menus'] as $menu)
{
if($menu) $selected[]=intval($menu);
}
$selectedlist=implode(",",$selected);
//The SQL Query
$query="SELECT name from restaurant WHERE menu in(".$selectedlist.")";
$record=mysql_fetch_array(mysql_query($query)); //Loop this to get more records
?>
Hope this is useful
The query below will return you the restids for restaurants that have both chicken and burger on the menu - assuming that restaurant_table doesn't have duplicate rows.
SELECT restid, COUNT(*) as cnt
FROM restaurant_table
WHERE menu IN ('chicken', 'burger')
GROUP BY restid
HAVING COUNT(*) = 2
Maybe this can help you as starting point:
$where = " 1=1 ";
if ( $_POST["chicken"] )
$where = $where . " AND menu = 'chicken' ";
if ( $_POST["Burger"] )
$where = $where . " AND menu = 'Burger' ";
if ( $_POST["fruits"] )
$where = $where . " AND menu = 'fruits' ";
$sql = "SELECT * FROM restaurants WHERE " + $where;

Categories