I am trying to set up a filter system for a small shop I am developing. Basically, I am working the results off a list of variables. the page, products.php if there is no querystring will show all products. However, if there is a variable present I want it to alter the select statement where necessary.
however, I am having problems filtering. If i use the AND statement for all variables it does not filter appropriately neither does the OR. So if i wanted black size 5 shoes it would show all size fives regardless of color.
Is there a better approach to take with this as is becoming a fair old head scratcher!
if ($queryString == NULL){
$query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id
GROUP BY store_products.prod_id";
}else{
$query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id
where store_products.sale='$sale' OR prod_color.color='$color' OR prod_sizes.size='$size' OR store_products.cat='$cat' GROUP BY store_products.prod_id";
}
example variable string
products.php?sale=&cat_id=1&size=&color=Yellow
Try building your WHERE criteria before running the query.
String:
products.php?sale=&cat_id=1&size=&color=Yellow
myfile.php
$criteria = "WHERE 1 ";
if (isset($_GET['sale']) {
$criteria .= "AND tore_products.sale=$_GET['sale'] ";
}
if (isset($_GET['cat_id']) {
$criteria .= "AND store_products.cat=$_GET['cat_id'] ";
}
if (isset($_GET['color']) {
$criteria .= "AND tore_products.color=$_GET['color'] ";
}
And so on then run your query:
$query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id
$criteria
GROUP BY store_products.prod_id";
And please remember to clean your $_GET variables prior to querying with them using mysql_real_escape_string, mysqli or PDO!
$query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id ";
if {$queryString != NULL){
$query .= " WHERE tore_products.sale='$sale' OR prod_color.color='$color' OR prod_sizes.size='$size' OR store_products.cat='$cat'"
}
$query .=" GROUP BY store_products.prod_id;"
Then you execute your Query :)
Related
I want to display all rows of table article, and for each of article row i want get the SUM of votes from another table (likes), and this with one query.
Here what i have:
$query = "SELECT article.title,article.tags,article.description,article.slug,users.username,article.photo,article.id,article.date,SUM(likes.votes) as upvotes
FROM article";
$query .= " LEFT JOIN users ON article.user_id = users.user_id ";
$query .= " LEFT JOIN likes ON likes.article_id = article.id ";
But my problem with this query, i get only one row ! because in table likes there only one row ...
I want to display results based on article table (i have about 50 rows in it)... and if there nothing related to votes for a specific article, we show (0 votes).
Thank you.
Add group by to the code :
$query = "SELECT article.title, article.tags, article.description, article.slug, users.username, article.photo, article.id, article.date, SUM(likes.votes) as upvotes FROM article";
$query .= " LEFT JOIN users ON article.user_id = users.user_id ";
$query .= " LEFT JOIN likes ON likes.article_id = article.id ";
$query .= " GROUP BY article.id";
Or use codeigniter method:
$this->db->select("article.title, article.tags, article.description, article.slug, users.username, article.photo, article.id, article.date");
$this->db->select("SUM(likes.votes) as upvotes", false);
$this->db->from("article");
$this->db->join("users","article.user_id = users.user_id");
$this->db->join("likes","likes.article_id = article.id");
$this->db->group_by("article.id");
$query = $this->db->get();
return $query->result_array();
A stored function is a special kind stored program that returns a single value. You use stored functions to encapsulate common formulas or business rules that are reusable among SQL statements or stored programs.
Here you query should
$query = "SELECT article.title,article.tags,article.description,article.slug,users.username,article.photo,article.id,article.date,custom_SUM(article.id) as upvotes
FROM article";
$query .= " LEFT JOIN users ON article.user_id = users.user_id ";
and custom mysql function
DELIMITER $$
CREATE FUNCTION custom_SUM(p_article_id int(11)) RETURNS VARCHAR(10)
DETERMINISTIC
BEGIN
DECLARE likes varchar(10);
SET likes =(select sum(likes.votes) from likes where likes.article_id=p_article_id);
RETURN (likes);
END
refer link here http://www.mysqltutorial.org/mysql-stored-function/
I have a query with multiple joins in it. After I take the results and run it through a Id-checker I want to be able to delete records from that array where the IDDestination equals $ID.
Since this query has joins on it and I am filtering them based on one of the joined tables, How do I go about deleting those records from the array based off that joined table?
And I only wanted this to happen after the user confirms.
$query = "
select d.IDCourse,
d.name as course_name,
d.slug,
d.short_description,
d.address,
e.city_name,
e.state_code,
d.zip,
e.city_slug,
e.state_slug,
h.IDDestination,
LOWER(e.iso_code) as country_slug, a.*,
b.IDTeetimeType,
c.name as teetime_type,
b.start_time,b.end_time,
(case dayofweek(a.teetime_dt)
when 1 then `b`.`sun`
when 2 then `b`.`mon`
when 3 then `b`.`tue`
when 4 then `b`.`wed`
when 5 then `b`.`thu`
when 6 then `b`.`fri`
when 7 then `b`.`sat`
end) AS `price`, g.tax_rate, f.alias
from cart_course_teetimes a
join course_priceplan b
on a.IDCoursePricePlan = b.IDCoursePricePlan
join course_teetime_type c
on b.IDTeetimeType = c.IDTeetimeType
join course d
on b.IDCourse = d.IDCourse
join vw_cities e
on d.IDCity = e.IDCity
join destinations_cities h
on h.IDCity= d.IDCity
LEFT JOIN (SELECT * FROM media_mapping WHERE is_main_item=1 AND IDGalleryType=3) f
ON d.IDGallery = f.IDGallery
left join course_tax
g on a.IDCourseTax = g.IDCourseTax
where a.IDCart = :cart_id
order by d.name, a.teetime_dt, b.start_time;";
$prepared = array(
"cart_id" => $idCart,
);
$conn = new DBConnection();
$results = $conn->fetch($query, $prepared);
$conn = null;
$results = !empty($results) ? $results : array();
$id = null;
foreach($results as $row) {
// Set ID for the first record.
if($id === null)
$id = $row['IDDestination'];
// will stay true, otherwise it's false and we should kill the loop.
if($id != $row['IDDestination']) {
$newid=$row['IDDestination'];
echo "<script type='text/javascript'> emptycart();</script>";
$query = "DELETE FROM cart_course_teetimes a WHERE h.IDDestination='.$id.'";
$res =mysql_query($query) or die (mysql_error());
break;
}
}
This is incorrect PHP:
$query = "DELETE FROM cart_course_teetimes a WHERE h.IDDestination='.$id.'"
You're already inside a "-quoted string, so . PHP concatenation operators aren't operators, they're just a period.
You want either of these instead:
$query = "DELETE FROM cart_course_teetimes a WHERE h.IDDestination='" . $id . "'";
$query = "DELETE FROM cart_course_teetimes a WHERE h.IDDestination='$id'"
Right now you're producing
... WHERE h.IDDestination = .42.
which is not valid SQL.
Plus it appears you're mixing database libraries. You've got $conn->fetch() which implies you're using one of the OO db libraries (mysqli? pdo? custom wrapper?). But you then call mysql_query(). Unless you've EXPLICITLY called mysql_connect(), that delete query will never execute. Database connections made in one of the libraries are utterly useless in any of the other libraries.
Im new to php and my sql in trying to get all the results from this table if nothing is selected but for some reason its always displaying one result. Any ide why
$query = "SELECT *, ROUND(AVG(d.rating),0) FROM restaurant AS r, review AS d WHERE 1=1 ";
if($vicinity) $query .= "AND r.vicinity=\"$vicinity\" ";
if($cuisine) $query .= "AND r.cuisine=\"$cuisine\" ";
if($price) $query .= "AND r.price=\"$price\"";
if($name) $query .= "AND r.name LIKE \"%$name%\"";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
and im only getting the first item on the table
I would look into PDO personally. You can find out a lot about it in the manual here.
guessing you're only getting one result because the avg call without a group by is triggering some interesting behavior. try adding a group by, and i'm guessing you also want to associate the restaurants and reviews with a join. eg:
$query = "SELECT *, ROUND(AVG(d.rating),0) FROM restaurant AS r LEFT JOIN review AS d on r.id = d.restaurant_id WHERE 1=1";
...
...
$query .= ' GROUP BY r.id';
$result = mysql_query($query);
per the thread, sounds like you should look into prepared statements as well :). and the SELECT * should probably also just be SELECT r.* - the data returned as part of the * results from the rating won't be meaningful after the group by (the r.* and round(avg(d.rating),0) values should be though)
Try to use prepared statements and get results and use iterator to parse and print in a loop will get. See also this tutorial.
I have a query I'm trying to build so that I can filter by car brand. But if a certain session variable exists, it'll ask for an extra part to be added to the query which is basically limiting the results to the logged in branch. Here's the query:
$query_AUCTION = "SELECT *
FROM at_auction AS a
JOIN at_brands AS b ON a.aCarBrandID = b.bid
ORDER BY b.brand $orderx";
... now this works but where can I add a:
"WHERE bid = '{$bid}'"? ...or a... "AND bid = '{$bid}'";
It brings up an error.
insert your where clauses BEFORE your order by
$query_AUCTION = "SELECT * FROM at_auction AS a JOIN at_brands AS b ON a.aCarBrandID = b.bid WHERE bid = '{$bid}' ORDER BY b.brand $orderx";
Use a generic WHERE 1=1 and if you want to insert additional condition:
$query_AUCTION = "SELECT *
FROM at_auction AS a
JOIN at_brands AS b ON a.aCarBrandID = b.bid
WHERE 1=1 ";
if ($bid > 0)
$query_AUCTION .= " AND bid = '{$bid}' ";
$query_AUCTION .= " ORDER BY b.brand $orderx";
try this :
$query_AUCTION = "SELECT *
FROM at_auction AS a
JOIN at_brands AS b ON ( b.bid = a.aCarBrandID ) ";
if( isset( $_SESSION['bid'] ) )
{
$query_AUCTION.= " WHERE b.bid = '".$_SESSION['bid']."'";
}
$query_AUCTION.= " ORDER BY b.brand $orderx";
Hey guys need some more help
I have 3 tables USERS, PROFILEINTERESTS and INTERESTS
profile interests has the two foreign keys which link users and interests, they are just done by ID.
I have this so far
$statement = "SELECT
InterestID
FROM
`ProfileInterests`
WHERE
userID = '$profile'";
Now I want it so that it selects from Interests where what it gets from that query is the result.
So say that gives out 3 numbers
1
3
4
I want it to search the Interests table where ID is = to those...I just don't know how to physically write it in PHP...
Please help.
Using a JOIN:
Best option if you need values from the PROFILEINTERESTS table.
SELECT DISTINCT i.*
FROM INTERESTS i
JOIN PROFILEINTERESTS pi ON pi.interests_id = i.interests_id
WHERE pi.userid = $profileid
Using EXISTS:
SELECT i.*
FROM INTERESTS i
WHERE EXISTS (SELECT NULL
FROM PROFILEINTERESTS pi
WHERE pi.interests_id = i.interests_id
AND pi.userid = $profileid)
Using IN:
SELECT i.*
FROM INTERESTS i
WHERE i.interests_id IN (SELECT pi.interests_id
FROM PROFILEINTERESTS pi
WHERE pi.userid = $profileid)
You are on the right track, lets say you execute the query above using this PHP code:
$statement = mysql_query("SELECT InterestID FROM `ProfileInterests`
WHERE userID = '$profile'");
Then you can use a PHP loop to dynamically generate an SQL statement that will pull the desired IDs from a second table. So, for example, continuing the code above:
$SQL = "";
while ($statementLoop = mysql_fetch_assoc($statement)) {
//Note the extra space on the end of the query
$SQL .= "`id` = '{$statementLoop['InterestID']}' OR ";
}
//Trim the " OR " off the end of the query
$SQL = rtrim($SQL, " OR ");
//Now run the dynamic SQL, using the query generated above
$query = mysql_query("SELECT * FROM `table2` WHERE {$SQL}")
I haven't tested the code, but it should work. So, this code will generate SQL like this:
SELECT * FROM `table2` WHERE `id` = '1' OR `id` = '3' OR `id` = '4'
Hope that helps,
spryno724
Most likely you want to join the tables
select
i.Name
from
ProfileInterests p
inner join
interests i
on
p.interestid = i.interestid
where
p.userid = 1