I'm trying to build a query using php and mysql,
$query = "select * from products where product_name = '$item_name'";
this works when $item_name holds only one name, but $item_name is an array and based on the user's interaction can contain multiple names, how can I make the query to run for multiple name and get the resulted rows.
Thanks in advance
Here's how you could build a safe list of names for inserting into an IN clause...
if (is_array($names) && count($names))
{
$filter="('".implode("','" array_map('mysql_real_escape_string', $names))."')";
$sql="select * from products where product_name in $filter";
//go fetch the results
}
else
{
//input was empty or not an array - you might want to throw an
//an error, or show 'no results'
}
array_map returns the input array of names after running each name through mysql_real_escape_string to sanitize it. We implode that array to make a nice list to use with an IN clause.
You should always ensure any data, particularly coming directly from the client side, is properly escaped in a query to prevent SQL injection attacks.
$vals = implode(',',$item_name);
$query = "select * from products where product_name in (".$vals.");";
Give that a try.
$query = "select * from products where product_name in(";
foreach($item_name as $name)
{
$query .= "'" . $item_name . "', ";
}
$query = substr($query, 0, strlen$query) - 2);
$query .= ");";
First answer (by inkedmn) is really the best one though
foreach($item_name as $name) {
$query = "select * from products where product_name = '$name'";
//whatever you want to do with the query here
}
something like that ought to do it.
Based on inkedmn's response (which didn't quote the item names):
$query = 'select * from products where product_name in ("' . implode('", "', $item_name ) . '")';
Although you may be better with a fulltext search.
http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html
Related
I'm working on a website that presents leaderboard data from a MySQL database as a table, that which can be filtered and searched through by the user. I was able to construct the table through PHP calls, such as
php echo $row['ranking'];
Similarly, I was able to create a pagination that limits the MySQL query to 50 rows per page.
What I haven't been able to achieve, is the filtering/searching of the data, as well as a pagination that doesn't require the reloading of the page. I attempted to create filtering through PHP variables
$sql = "SELECT * FROM New_2v2_Data $filters";
but couldn't get it to work outside of just editing the PHP code.
$racevar = '%';
$classvar = '%';
$specvar = '%';
$playervar = '%';
$realmvar = '%';
$factionvar = '%';
$r1 = '0';
$r2 = '1800';
$race ="raceId LIKE '$racevar'";
$class = "classId LIKE '$classvar'";
$spec ="specId LIKE '$specvar'";
$player ="player LIKE '$playervar'";
$realm ="realmName LIKE '$realmvar'";
$faction="factionId LIKE '$factionvar'";
$rating ="rating between $r1 and $r2";
$filters = "WHERE $race AND $class AND $spec AND $player AND $realm AND $faction AND $rating";
$sql = "SELECT * FROM New_2v2_Data $filters";
$rs_result = mysql_query ($sql); //run the query
I've found filtering solutions for individual variables, for example names, but I haven't been able to find anything that takes in multiple variables into account. Even then, the filtering only worked on tables that were static.
I was thinking maybe if a dropdown/checkbox were to change a PHP variable depending on what is chosen, and then reloading the PHP for the table to include the additional "WHERE" statement, filtering could work.
Some advice on how I would go about doing this would be great, thank you.
You can conditionally include the various limits and build the SQL just from those which have something set.
$racevar = 'a'; // A value to show when this would be included
$classvar = '%';
$specvar = '%';
$playervar = '%';
$realmvar = '%';
$factionvar = '%';
$r1 = '0';
$r2 = '1800';
$condition= [];
$bindData = [];
if ( $racevar != '%'){
$condition[] ="raceId LIKE ?";
$bindData[] = $racevar;
}
if ( $classvar != '%'){
$condition[] = "classId LIKE ?";
$bindData[] = $classvar;
}
// Repeat above for all of the conditions
if ( $r1 != 0 or $r2 != 0 ) {
$condition[] = "rating between ? and ?";
$bindData[] = $r1;
$bindData[] = $r2;
}
$sql = "SELECT * FROM New_2v2_Data";
if ( count($condition) > 0 ) {
$sql .= " WHERE ".implode(' and ', $condition);
}
echo $sql;
The idea is to build a list of conditions, only when the values have something which is a limit. This can then be added as a where clause.
You then can have various input fields/select fields which allow the user to select the criteria and call this routine with the selections.
I've updated the answer to use bind variables, so that using prepare will give you more security and then you can either bind the values or (using PDO) execute with the array of bind values.
You need to make the filters selectable or dynamic in a way that you can pass them on to your SQL statement.
Your solution for the dropdown could be one of them indeed. You could even do that with a 'search' input text field. Then you make your WHERE statement:
WHERE (`column1` LIKE '%$search%' OR `column2` LIKE '%$search%' OR `column3` LIKE '%$search%',) LIMIT 0,10
How make mysql search defined just by what is written in html form, by user, and if some form box is stayed empty, mysql should ignore it. For example:
$sql = "SELECT * FROM catalog WHERE name= '".$name."' AND publisher = '".$publisher."' ";
mysql_query($sql);
This query will display all rows where name and publisher are together. Now, what if user insert just name, and left publisher box empty. The idea is that php/mysql ignore empty form box, and display every row with inserted name. But it will not do that because $publisher will be undefined, and error emerges. How to tell musql to ignore $publisher? More generally, the question is: how to generate query that make searching defined by certain criteria if they exists, and if they don't how to just ignore it?
You can build up the sql programmatically. I am assuming you have escaped the values properly.
$sql = "SELECT * FROM catalog";
$wheres = array();
if (!empty($name)) {
$wheres[] = " name = '$name'";
}
if (!empty($publisher)) {
$wheres[] = " publisher = '$publisher'";
}
if (count($wheres)) {
$sql .= " WHERE " . implode (' AND ', $wheres);
}
//RUN SQL
Also have a read through this, you are using a deprecated mysql library.
This will allow either the name or the publisher to be NULL.
<?php
$sql = "SELECT * FROM catalog WHERE (name= '".$name."' OR name IS NULL) AND (publisher = '".$publisher."' OR publisher IS NULL)";
mysql_query($sql);
Try like
$my_var = " ";
if($publisher) //if(!empty($publisher))
$my_var = " AND publisher = '".$publisher."' ";
$sql = "SELECT * FROM catalog WHERE name= '".$name."' ".$my_var;
if the publisher is empty then you need to pass the NULL value and PLZ note that it is a bad practise.It will causes many sql injection issues.Try to put validations for the things
I have a php code with a query:
$query = "SELECT * FROM TDdb WHERE status = $status AND occupation =$occupation";
I am sending the values status and occupation with a client application to this php code.
This works when I send both status and occupation. But I want it to return rows if I just send status but not occupation also ( I mean no matter what the occupation is).
does anyone have any suggestions?
I would appreciate any help.
PS: I want to do it without if statement and just but changing the query
Personally I would create a base query and append conditions wherever you have them, like so:
$sql = 'SELECT * FROM TDdb';
$conditions = array();
$args = array();
if ($action) {
$conditions[] = 'status = :status';
$args[':status'] = $status;
}
if ($occupation) {
$conditions[] = 'occupation = :occupation';
$args[':occupation'] = $occupation;
}
if ($conditions) {
$sql .= ' WHERE ' . join(' AND ', $conditions);
}
$stmt = $db->prepare($sql);
$stmt->execute($args);
Looks like you've got a few good options for how to do it in SQL, or how to make the SQL string variable in PHP.
One reason to consider using an 'if' in the PHP code for the database access performance.
When you introduce an 'or' condition like that in SQL, you're not going to get index access. It is much harder for the database to determine what path it should take than for the PHP code because the SQL engine optimizes the query without knowing what the variable will resolve to at execution.
You already know in the PHP which version of the query you really want. This will perform better if you make that choice there.
This will work if you pass an occupation or a NULL value.
SELECT *
FROM TDdb
WHERE status = $status
AND ($occupation IS NULL OR occupation = $occupation)
"SELECT * FROM TDdb WHERE status = '$status' AND (occupation = '$occupation' OR occupation IS NULL)";
Apart from the solution provided by #Tom and #Damien Legros, you may create two query strings one with occupation and one without occupation. Something like:
$query = "SELECT * FROM TDdb WHERE status = $status";
if ($occupation != "") {
/*When you have value for occupation*/
$query .= " AND occupation =$occupation";
}
So in this case, data will be returned if you have only the status field. Secondly, please check if the status and occupation fields in table are varchar then you have to enclose them in single quotes (').
Thanks everyone for help. specially jack.
finally i created my query like this:
$query = 'SELECT * FROM TDdb';
if ($status) {
$query = $query." WHERE status = '".$status."'";
}
if ($occupation) {
$query = $query." AND occupation = '".$occupation."'";
}
I have a search script that retrieves an integer from one table and uses it to search through the IDs of a 2nd table. My issue is if the integer in Table1 appears more then once, I get duplicate results when querying Table2.
Does anyone know a way to use SQL or PHP so that if a row is already displayed it will skip it? Thanks
My code is rather convuleted but here it is if it helps:
//TV FILTERS
$sql = 'SELECT * FROM `table1`';
$where = array();
if ($searchlocation !== 'Any') $where[] = '`value` LIKE "%'.$searchlocation.'%"';
if ($searchmake !== 'Any') $where[] = '`value` LIKE "%'.$searchmake.'%"';
if ($searchtype !== 'Any') $where[] = '`value` LIKE "%'.$searchtype.'%"';
if (count($where) > 0) {
$sql .= ' WHERE '.implode(' OR ', $where);
} else {
// Error out; must specify at least one!
}
$tvqresult = mysql_query($sql);
$num_rowstvq = mysql_num_rows($tvqresult);
while ($rowtvq = mysql_fetch_array($tvqresult)) {
$contid = $rowtvq['contentid'];
//MAIN QUERY
$mainsql = 'SELECT * FROM `table2` WHERE `content` LIKE "%' . $searchterm . '%" AND `id` = ' . $rowtvq['contentid'] . ' AND `template` = 12';
$resultmain = mysql_query($mainsql);
$num_rowsmain = mysql_num_rows($resultmain);
if (!$resultmain) {
continue;
}
else {
while ($row = mysql_fetch_array($resultmain )) {
echo "[!Ditto? &parents=`134` &documents=" . $row['id'] . "&tpl=`usedtempchunk`!]";
}//END MAIN LOOP
}//END MAIN ELSE
}//END TV WHILE LOOP
You only seem to use the contentid column from your first query, so you could change it to:
$sql = 'SELECT distinct contentid FROM `table1`'; // rest would be the same
which would mean that no duplicates will be retreived saving you any hassle in changing your second set of code.
If you are using other columns from the first query somewhere else in your code, you can still fetch more columns with this method as long as there are no duplicate IDs:
$sql = 'SELECT distinct contentid, contentTitle, contentThing FROM `table1`';
If you have to have repeated IDs in your original query, I think you will have to store the data in a variable (like an array) and then make sure that the second dataset isn't repeating anything.
It sounds like you're only looking for 1 row, if so, then at the end of your SQL, simply add LIMIT 1. That'll ensure you only return 1 row, thereby ignoring any duplicate matches.
I'm currently coding a simple search script in PHP that requires three variables from the user namely:
$Capacity, $Location and $RoomType
Capacity is a required field which the jquery validate plugin checks for numerical entry on input - but Location and RoomType are optional.
I'm trying to now draft a SQL query that will search the table rooms.
There are three columns in the table also called Capacity, Location and RoomType that I want to search using the variables.
How would I write this SQL query? Especially with $Capacity being required, $Location / $RoomType expected to be left blank or filled in at the users discretion?
You could use LIKE ...% in your sql query, so that even when blank, it'll be treated as a wildcard.
$q = 'SELECT * FROM foo WHERE capacity = "'.$capacity.'" AND location LIKE "'.$location.'%" AND roomtype LIKE "'.$roomtype.'%"';
Of course, remember to escape the inputs.
Something like this should work:
function BuildSearchQuery($Capacity, $Location, $RoomType)
{
$where = array();
if (!empty($Capacity))
{
$where[] = "Capacity = '" . mysql_real_escape_string($Capacity) . "'";
}
if (!empty($Location))
{
$where[] = "Location = '" . mysql_real_escape_string($Location) . "'";
}
if (!empty($RoomType))
{
$where[] = "RoomType = '" . mysql_real_escape_string($RoomType) . "'";
}
if (empty($where))
{
return false;
}
$sql = "select * from `table` where ";
$sql += implode(" AND ", $where);
return $sql;
}
Although nowadays many frameworks exists that allow you to do this more easily and less error-prone than manually crafting queries.
$query =select * from table where Capacity =$Capacity
if(isset($Location) && $Location!='') $query.= and Location LIKE '%$location%'
if(isset($RoomType) && $RoomType!='') $query.= and RoomType LIKE '%$RoomType%'
Making use of LIKE or = operator in query is upto you.
Depend on how complex it is (and or not ???)
But basically
Select ... From Rooms Where Capacity = #Capacity
and ((Location = #Location) Or (IsNull(#Location,'') = ''))
and ((RoomType = #RoomType) or (IsNull(#RoomType,'') = ''))
Or some such.
If you aren't using parameterised queryies then replace #.... with the escaped inputs.