Query where clause based on user input - html

I have some html that allows the user to search with 2 criteria: name and cost. I am trying to make it so that the query displays results based on what the user enters for name and cost. There are 3 cases: name entered no cost, cost entered no name, both entered
SELECT name, cost FROM table WHERE...
I know to get the values entered by doing $_POST['name'] and $_POST['cost'] but I am struggling on how to set up the query to display the information based on the possible user input combinations

Is this what you basically want?
select . . .
from t
where (name = #name or #name is null) and
(cost = #cost or #cost is null);
Here #name and #cost are parameters used to pass the user input values into the query.

For my case, I always arrange the SQL like below:-
$nane = $_POST['name']:
$cost = $_POST['cost'];
if((isset($nane) && ($nane != "")) && (isset($cost) && ($cost != "")))
{
$sql = "select name,cost from table where columnNm ='".$nane."' and columnNm1 = ".$cost;
}
else if((isset($nane) && ($nane != "")) && (!isset($cost) && ($cost == "")))
{
$sql = "select name,cost from table where columnNm ='".$nane."'";
}
else if((!isset($nane) && ($nane == "")) && (isset($cost) && ($cost != "")))
{
$sql = "select name,cost from table where columnNm1 = ".$cost;
}
I solve my issues like this. If you think it's suitable for you then you may use it.

Related

How to simplify this so that search takes less time?

string name = null;
foreach (var dealer in contact)
{
if (name != null)
break;
if (name == null)
{
foreach (var emp in dealer.employees)
{
if (emp.id == primarySalespersonId)
{
if (emp.personFirstName != null)
name = emp.personFirstName;
else
name = "No Name";
break;
}
}
}
There are same multiple tables named contact. And each contact table has multiple dealer tables. I need a method to simplify this search using LINQ or any other better way. Please Help
The first optimisation you can do is to replace the inner loop to look for the employee by id, eg
string name = null;
foreach (var dealer in contact)
{
var emp= dealer.employees.Where(e=>e.Id == primarySalespersonId).FirstOrDefault();
if (emp!= null)
{
if (emp.personFirstName != null)
name = emp.personFirstName;
else
name = "No Name";
}
if (name != null)
break;
}
Going further, requires making some assumptions.
When a table has a column named 'id, then I would assume it means the column is an unique identity column.
If contact represents every dealer (as opposed to a selection of dealers) and if every employee belongs to a dealer, then you should be able to look up the id directly.
var emp = employees.Where(e=>e.Id == primarySalespersonId).SingleOrDefault();
if (emp != null)
{
if (emp.personFirstName != null)
name = emp.personFirstName;
else
name = "No Name";
}

retrieve only the data from the rows those are not empty

suppose I have 2 columns username and password and I want to retrieve only the data from the rows those are not empty. how to do it in php or mysql? Plz provide solution in both php and mysql.
from the comments
I tried this SELECT * FROM users WHERE username IS NOT NULL AND username != " " and it works only for one column. What if I have to check empty fields for multiple columns?
Try this:
if((!name.eual(""))and(!password.equal("")){
// code here
}
SELECT username, password FROM table_name WHERE table_name.username!='' AND table_name.password!='';
In case you do select everything even the blank rows. with SELECT * FROM table_name
In your php assuming that $data is the output of your query do a loop like this
foreach ($arr as $key => $value){
if(($key == 'username' && $value == '') || ($key == 'password' && $value == '')){
// row with blank username and password.
}
}
$query="SELECT * FROM users WHERE username IS NOT NULL AND password IS NOT NULL"

MYSQL query with variables that may not be set

I have a PHP file which is taking in seven variables like so:
$name=$_REQUEST['membername'];
$email=$_REQUEST['email'];
$dob=$_REQUEST['dob'];
$gender=$_REQUEST['gender'];
$phone=$_REQUEST['phone'];
$county=$_REQUEST['county'];
$IP=$_REQUEST['IP'];
Some of these will not be set. What I want to do is construct a query which will search the members table such that if only $email and $dob are set it will only search by $email and $dob, ignoring the others. Or if only $phone, $name, and $gender are set, it will search those three columns only.
Is there an easier method than constructing a big block of if isset functions covering all possible permutations?
If you don't want to search on a field, pass NULL for the parameter and structure your WHERE clause something like...
WHERE
( (#parameter1 IS NULL) OR (column1 = #parameter1) )
AND
( (#parameter2 IS NULL) OR (column2 = #parameter2) )
I don't spend much time in MYSQL so the syntax is probably a bit off but you get the idea.
Presuming that you use parameters to push values into the query...
SELECT *
FROM MyTable
WHERE name = COALESCE(#p1, name)
OR email = COALESCE(#p2, email)
OR dob = COALESCE(#p3, dob)
...
...
If you construct a query string in PHP you can, instead, take another tack:
function AddWhere(&$where, $dbFieldName, $fieldValue)
{
if ($fieldValue <> "")
{
if (strlen($fieldName) > 0)
$fieldName .= " AND ";
$fieldname .= '(' + $dbFieldName + ' = \'' + $fieldValue + '\')'
}
}
Then, when you're retrived the variables, build a SQL statement thusly
$whereClause = ''
AddWhere($whereClause, 'name', $name)
AddWhere($whereClause, 'email', $email)
AddWhere($whereClause, 'dob', $dob)
...
IF (strlen($whereClause) > 0)
{
$sql = 'SELECT * FROM MyTable WHERE ' + $whereClause
... etc
}
(I'm not great at PHP, so the syntax may be somewhat screwed up).

"ERROR: Only one expression can be specified in the select list" Linq To Sql

var loggedInHours = db.LoginLogs.Where(l => l.UserId == u.Id && l.UserSessionStop != null)
.Sum(ls=> ls.UserSessionStart.Subtract(ls.UserSessionStop.Value).Hours)
I am trying to calculate Total LoggedIn Hours using this linq query..
But its giving me this error
"Only one expression can be specified in the select list when the subquery is not introduced with EXISTS."
I don't know whats wrong with it..plz help
Try if this works:
var loggedInHours = db.LoginLogs.Where(l => l.UserId == u.Id && l.UserSessionStop != null)
.Select(l=> new {
StartTime = l.UserSessionStart,
EndTime = l.UserSessionStop
})
.ToList()
.Sum(c=> c.StartTime - c.EndTime);
btw, Is UserSessionStop nullable? If yes, then what will be the value to be subtracted?

LINQ to SQL Query Where Clause

I would like to create a single query that "adjusts" it's where clause based on a tuple. The first item in the tuple contains a enum value indicating the field in which to filter. The second tuple item is the filter value.
Notice the query below does not work:
var query = from p in db.Categories
where ( QueryBy.Item1 == CategoryFields.Name && p.Name == (string)(QueryBy.Item2) ) ||
( QueryBy.Item1 == CategoryFields.Id && p.Id == (long)(QueryBy.Item2) ) ||
( QueryBy.Item1 == CategoryFields.Description && p.Description == (string)(QueryBy.Item2) ) ||
( QueryBy.Item1 == CategoryFields.SortOrder && p.SortOrder == (int)(QueryBy.Item2) )
select...
if (query.Count() == 1) // ERRORS HERE CONVERSION OF INT
A similar query with only this where clause change will works:
var query = from p in db.Categories
where ( QueryBy.Item1 == CategoryFields.Name && p.Name == (string)(QueryBy.Item2) )
select...
if (query.Count() == 1) // Works HERE
Any idea what could be wrong? Can it be that LINQ where clause perform a short-circuit evaluation and thus the cast of item2 fails? Is there a better way to accomplish my overall goal of adjusting where clause?
Thanks in advance for your help!
LINQ to SQL isn't smart enough to optimize your query and generate it dynamically based on the value of your QueryBy.Item1. It will simply generate a SQL query let SQL server decide this for itself.
When you know that, the error makes sense, since it's impossible for one single value to be castable to both int, long, and string.
In your case you would be better of dynamically generating the right where clause. You can do this with the PredicateBuilder:
IQueryable<Category> query = db.Categories;
var whereClause = PredicateBuilder.False<Category>();
switch (QueryBy.Item1)
{
case CategoryFields.Name:
long id = (string)QueryBy.Item2;
whereClause = whereClause.Or(p => p.Name == name);
break;
case CategoryFields.Id:
string name = (string)QueryBy.Item2;
whereClause = whereClause.Or(p => p.Id == id);
break;
case CategoryFields.Description:
string des = (string)QueryBy.Item2;
whereClause =
whereClause.Or(p => p.Description == des);
break;
case CategoryFields.Id:
string sort = (int)QueryBy.Item2;
whereClause =
whereClause.Or(p => p.SortOrder == sort);
break;
}
query = query.Where(whereClause);