PHP MYSQL syntax - php

I'm having a little trouble with my MYSQL query
I have a DB full of products and I have a dropdown menu which lets a user select what time of day they'd like to get get results for :-
Dropdown
Breakfast
Lunch
Evening
Anytime
At the moment my statement is
SELECT * from DEALS WHERE timeofday='post data from form';
Now this works fine, but with the option for 'Anytime' I'd like the query to be able to search for results of all/any of the above.
I was thinking of perhaps doing an IF statement which fires off 2 separate queries, one which says if the $_POST['timeofday'] == 'Anytime' then fire off
SELECT * from DEALS where timeofday='Breakfast'
OR timeofday='Lunch' OR timeofday='Evening';
otherwise just do the normal query, although wondered if it was possible to do this in just one statement.
Kind regards

$query = 'SELECT * from DEALS';
if ($_POST['timeofday'] != 'Anytime') {
$query .= ' WHERE timeofday="' . $_POST['timeofday'] . '"';
}
As DCoder mentioned, this approach is vulnerable to sql injection... You should check/sanitize the input or use prepared statements. In this case where there is a predefined set of values you can:
$knownTimesOfDay = array('Breakfast', 'Lunch', 'Evening', 'Anytime');
if (!in_array($_POST['timeofday'])) {
die('Unsuppotred time of day... Did it really come from the form?');
}
$query = 'SELECT * from DEALS';
if ($_POST['timeofday'] != 'Anytime') {
$query .= ' WHERE timeofday="' . $_POST['timeofday'] . '"';
}

Don't think it can be done in one statement.
You are going to have to use an if statement anyhow.

if these are the only 3 possible values for timeofday,then you can have an if in the php script like this:
if($_POST['timeofday'] != 'Anytime' )
sql .= "where timeofday='".$_POST['timeofday']."'";

This could turn out to be negative depending on the items you have in the table, but you could use:
SELECT * from DEALS where timeofday LIKE '%{$post_data}%'
It would return all the results from timeofday if $post_data was an empty string.

Related

Advanced Search PHP

I have an advanced search with 4 fields, only one name_first is mandatory
There are many variations of search as the other fields are not mandatory so I need a select statement that only selects the fields that have been populated, but there are so many variations
I have tried the below script but it does not show the correct information (I think it is completely wrong?!)
$name_first=$_GET["name_first"];
$status=$_GET["status"];
$type=$_GET["type"];
$manstaff=$_GET["manstaff"];
$result401=mysql_query("SELECT * FROM `hr_employees` WHERE
(name_first LIKE '$name_first%')
AND
(status LIKE '$status%')
AND
(manages_staff LIKE '$manstaff%');")or die('Error' . mysql_error());
Any ideas what the script above should be? Basically if the field isnt completed it doesnt need to search for it?
First define your SQL with only the required criteria
$sql = "SELECT * FROM `hr_employees` WHERE (name_first LIKE '$name_first%')";
then add the optional criteria... optionally
if ($status) {
$sql .= " AND (status LIKE '$status%') ";
}
if ($manstaff) {
$sql .= " AND (manages_staff LIKE '$manstaff%')";
}
$result401=mysql_query($sql) or die ('Error' . mysql_error());
Incidentally, please consider updating your code to avoid using the deprecated mysql functions, and keep in mind that concatenating variables into your SQL like this makes your code vulnerable to SQL injection.

SQL, ignore where cause if PHP value is empty

Does anyone know how to get a mysql query to ignore a certain where condition if the PHP value is empty. I am trying to create an advance search engine with many strict where conditions to filter search, but would like the SQL to ignore some of the where causes if the PHP value is empty.
For example:
$condition_1 = ' ';
$condition_2 = 'Random';
mysql_query("SELECT something FROM table WHERE row_1='$condition_1' && row_2='$condition_2'")
There will be 15 where causes in the query, so anything that involves making multiple queries for different combination of searches is not doable.
$condition_1 is empty and will show results to only those with no value in row_1 , but I just want to have the query ignore the row_1 condition when the PHP value, $condition_1, is empty. How would I do this?
You can construct your where condition dynamically, note that this also works if both conditions are empty
$sql = "SELECT something FROM table where 1 ";
if(trim($condition_1) != '')
$sql .= " AND row_1='$condition_1'";
if(trim($condition_2) != '')
$sql .= " AND row_2='$condition_2'";
mysql_query($sql);

Variable mysql statement in php

I have a variable that is a filter for my query:
$filterString.=" AND venue = ".$venue;
And I want this variable (when called) to add the AND filter statement to my query.
My query is as follows (with the failed attempt):
mysql_query("SELECT * FROM event
WHERE city = '$city' " . $filterString . "
ORDER BY date ASC");
I think the venue needs to be surrounded by single quotes:
$filterString.=" AND venue = '".$venue.".";
However, it is better to use parameterized queries, instead of embedding queries directly in the SQL string.
You could use:
$filterString .= !empty($venue) ? " AND venue = '$venue'" : '';
Substitute whatever test you want at the start, the idea is to return a blank string if $venue doesn't apply to the filter.
To answer your other comment question:
WHERE 1
is a valid condition that works like Anything

Mysql WHERE clause help

How can I use a WHERE MySQL clause in a statement which can fetch me all the records? I am settings the WHERE condition conditionally. Like...
if (this) {
$mycondition=1;
} elseif (that {
$mycondition=????
}
'SELECT * FROM table WHERE category='.$mycondition
What should be the value of ???? so that when I pass it to the sql statement it fetches me all the records. I was thinking that WHERE category='*' might work but it does not.
You need to build your WHERE condition piece by piece :
start with an empty array
add some conditions depending on search form input (like add "category=1" or "name like ...")
implode( " AND ", $array ) will stick the conditions together
concatenate this in your SQL
if there is no condition, don't put a where clause
The best answer is not to have a WHERE clause at all, as suggested as part of peufeu's answer if you don't have a condition to be met:
SELECT * FROM table;
Is perfectly valid.
However, if you are in a situation where you must have a WHERE clause (or where it's drastically easier to have one), do as Nanne suggests, and put an "always true" condition as your first clause, so something like:
$query = 'SELECT * FROM TABLE WHERE true';
if (this) {
$query = $query . ' AND column=this';
}
You could just use this
if(this){
$mycondition=" category=1";
}elseif(that{
$mycondition= " 1"; //1 = 'true'. You could also use "1=1
}
'SELECT * FROM table WHERE '.$mycondition

SQL query building practices

I am building a SQL query that dynamically changes based on passed in $_GET parameters. I simply want to know if putting in a 'dummy' constraint is an 'acceptable' practice, so I do not have to check the SQL string for the existence of 'where' before I add new constraints (each time).
For example, the 'dummy' constraint':
$sql = "select * from users u where u.id != 0";
Now, in each block where I determine if I have to add more constraints, I can just do:
if (!empty($uid))
$sql .= " and (u.id = {$uid})";
Instead of doing:
if (!empty($uid)) {
$sql .= strpos($sql, "where") === false ? " where " : " and ";
$sql .= " (u.id = {$uid})";
}
I've used that convention (although I usually use WHERE 1=1 AND.) Depending on your RDBMS, using a column there could affect performance. For example, if you had an index that would otherwise be a covering index except for that column.
Please make sure that you understand the potential pitfalls of this kind of dynamic SQL, but if it's what you ultimately end up doing, adding that extra bit seems to make sense to me.
Instead of appending to the SQL string for each check, you could collect the conditions:
if ($_GET["uid"]) {
$where[] = array("u.id =", $_GET->sql["uid"]);
if ($_GET["photo"]) {
$where[] = array("u.has_photo =", 1);
And complete the SQL string when you're through:
foreach ($where as $add) {
$sql .= ...;
}
Otherwise, it's an acceptable approach. I wouldn't turn out the big weapons and use a full blown ORM query builder for that.
from the manual
SELECT * FROM table WHERE 1
so yes, you can do that

Categories