Search Multiple Items in Multiple columns - php

I have 6 select items in a form. I want to search those 6 in MYSQL DB. I can retrieve results if I use only one, like:
$result = mysql_query("SELECT * FROM wsinmuebles WHERE Property_Type LIKE '%{$_POST['Property_Type']}%'");
But when I try more, I get no results!
$result = mysql_query("SELECT * FROM wsinmuebles WHERE
Property_Type LIKE '%{$_POST['Property_Type']}%' AND
Estado LIKE '%{$_POST['Estado']}%' AND
Ciudad LIKE '%{$_POST['Ciudad']}%' AND
Urbanizacion LIKE '%{$_POST['Urbanizacion']}%' AND
Operacion LIKE '%{$_POST['Operacion']}%' AND
Precio_bsf LIKE '%{$_POST['Precio_bsf']}%'");
This comes from a form by the POST method.
What I need is to look for Property_Type, Estado, Ciudad, Urbanizacion, Operacion and Precio_bsf variables in MYSQL DB, and receive only the results that match all those values.

First, escape the post values using mysql_real_escape_string (Link) to avoid any SQL injection attacks and also issues with the data having ' characters.
Second echo the query and run it against the database and check the table data to see if the
query indeed should return some values or may be there are no matches when include the rest of criteria since you mentioned that you are expecting the results that match all those values.

Dont use And use Or between criteria, and after all you should know that concatenating strings and executing queries is giving possible SQL Injection, that is when instead of your search string I end your query and execute given action, for example "' and 1=1; delete wsinmuebles" if this is my serach query you will lose all your data.
$result = mysql_query("select * from tbl1 where Name='".mysql_escape_string ($_POST["value"]."'" );

If a field, say Urbanizacion is null, your query will not return it.
Urbanizacion LIKE '%%' => FALSE when Urbanizacion is Null
You will need to handle Nulls. I also strongly urge you to protect the code from SQL Injection using mysql_real_escape_string
$result = mysql_query("
SELECT * FROM wsinmuebles WHERE
IFNULL(Property_Type,'') LIKE '" . mysql_real_escape_string($_POST['Property_Type']) ."' AND
IFNULL(Estado,'') LIKE '" . mysql_real_escape_string($_POST['Estado']). "' AND
IFNULL(Ciudad,'') LIKE '" . mysql_real_escape_string($_POST['Ciudad']) ."' AND
IFNULL(Urbanizacion,'') LIKE '" . mysql_real_escape_string($_POST['Urbanizacion']) ."' AND
IFNULL(Operacion,'') LIKE '" . mysql_real_escape_string($_POST['Operacion']) ."' AND
IFNULL(Precio_bsf,'') LIKE '" . mysql_real_escape_string($_POST['Precio_bsf']) ."'");

Related

PDO changes query

I want to have result of my query as it was before I replaced db connection using PDO. How can I get the query as i t was before I implemented PDO?
This is my query:
$query =
"SELECT
`id_affirmation`,
`affirmation`,
`author`,
`user_rate`,
am.date,
am.time,
hua.date,
hua.time
FROM `affirmation_male` am
JOIN `history_user_affirmation` hua ON am.id_affirmation = ua.affirmation_id
WHERE hua.user_id = '" . $id_user . "'
ORDER BY
STR_TO_DATE(hua.date, '%d-%m-%Y') DESC,
hua.time DESC";
For some reason the result of query when I use PDO is i got date from affirmation_male. Do you know why?
Your query returns two columns that have the same name, hence PDO gets lost when it fetches the results; since each records is represented as an associative array, duplicate keys generate ambiguity (only one key will be retained).
You would need to alias those columns to remove ambiguity:
$query =
"SELECT
`id_affirmation`,
`affirmation`,
`author`,
`user_rate`,
am.date am_date,
am.time am_time,
hua.date AS hua_date,
hua.time AS hua_time
FROM `affirmation_male` am
JOIN `history_user_affirmation` hua ON am.id_affirmation = hua.affirmation_id
WHERE hua.user_id = '" . $id_user . "'
ORDER BY
STR_TO_DATE(hua.date, '%d-%m-%Y') DESC,
hua.time DESC";
Notes:
it would also be a good idea to prefix the first columns in the query with the alias of the table they belong to, as this makes the query more readable (and will avoid conflicts if ever these columns names were available in more than one table coming into play in the query)
you could remove backticks to make the query more readable, as the column and table names that you are quoting do not seem to contain any special characters

mysql like query not working on browser

I have below query which works fine when given the exact column value but when used like operator it can't fetch any rows . how to pass % sign on the below query
$RegistrationMark = $_GET['RegistrationMark'];
$qr= mysqli_query($connection, "SELECT * FROM `EarlsdonMSIN_anpr_vega` where `RegistrationMark` like '" %.$RegistrationMark. %"'");
Your % marks are in the wrong place...
$qr= mysqli_query($connection, "SELECT * FROM `EarlsdonMSIN_anpr_vega` where `RegistrationMark` like '%" .$RegistrationMark. "%'");
You should be careful with using concatenated strings and SQL injection hacks.

Select SUM() as a variable in a for Loop

I'm trying to generate XML from database and need to gather a specific amount of data based on the average from a column. This can vary from anywhere between 5 to 30 queries for the $numItems variable.
I need to execute a for loop and assign the column name in the SUM($variable) but I'm not getting any data (but no errors either).
Here is my code:
for ($t = 1; $t <= $numItems; $t++){
$query = mysql_fetch_assoc(mysql_query("SELECT SUM(column'".$t."') AS value_sum FROM scoring WHERE ID='" . $userID . "' AND name ='" . $name . "'"));
$q = $query['value_sum'] / $totalUsers;
echo "<output".$t.">" . $q . "</output".$t.">\n";
}
The problem is assigning the SUM(column1) variable name for the column I'm getting data from, when I write the queries individually it works, but assigning the variable within the statement is causing a problem. Can any one give me any pointers?
Thanks in advance.
It looks like you might have extra single quotes in your query. I think it should be:
"SELECT SUM(column".$t.")..."
You should also consider doing a single select. Doing multiple database calls inside a for loop will be a huge performance problem. You could write a single select like this:
"SELECT SUM(column1), SUM(column2), SUM(column3),..."
Looks like bad escaping/concatenation around the column name...
"SELECT SUM(column{$t}) AS value_sum FROM scoring WHERE ID='{$userID}' AND name ='{$name}'"
Is that what you want?
Also use PDO!

Using PHP & MySQL to sort Events by multiple types.

I need to create a small piece of code to allow me to filter my events database based on category types users have selected.
I currently have it working for users who have only one category selected...
$user_qstring = "SELECT types FROM tbl_users WHERE user_id='".$_SESSION['id']."'";
$user_result = mysql_query($user_qstring);
$user_row = mysql_fetch_array($user_result);
$type_filter = $user_row['types'];
if(isset($type_filter) && $type_filter !="") {
$day_events = "SELECT COUNT(*) FROM tbl_events WHERE day='".$day_id."' AND
type='".$type_filter."'";
}else{
$day_events = "SELECT COUNT(*) FROM tbl_events WHERE day='".$day_id."'";
}
I need to alter this code so that if $type_filter is set and contains multiple categories in the following format.
Festivals,Sports,Education
And have the query automatically add...
OR type='".$type_filter[2]."' OR type='".$type_filter[3]."' OR ect...
I have been able to solve the problem using multiple...
elseif(){
}
Statements, but need a solution that is scalable to unlimited types.
I know I need to start by changing $type_filter to a list using explode...
$type_filter = explode(",", $user_row['types']);
But I'm still having trouble putting it all together for a short elegant solution.
You will need to confirm that $type_filter does not contain single quotes first otherwise you're an easy target for sql injection attacks.
$day_events = "SELECT COUNT(*) FROM tbl_events WHERE day='".$day_id."' AND type IN ('" . implode("','", explode(',', $type_filter)) . "')";
try something like the follwing sql
select * from ... where type in ('one', 'two', ...) ...
and as a remark - always escape get/post data using mysql_real_escape_string or you are vulnerable to injection attacks.

WHERE IN SQL condition problem

I have this query:
"SELECT * FROM informations WHERE ". $id ." IN (ids)"
It only works if $id is the first value from ids... in ids values are "1,2,3,4,5".
Is there a way for it to work with the rest of the ids?
Would this work for you?
"SELECT *
FROM Informations
WHERE ids LIKE \"" . $id . ", %\" -- try to match against the first value in ids
OR ids LIKE \"%," . $id . ",%\" -- try to match against a value in ids that is neither the first nor the last value
OR ids LIKE \"%," .$id . "\" -- try to match against the last value found in ids"
If ids is a field containing comma-delimited values, then your query is like:
SELECT * FROM `informations` WHERE 3 IN ("1,2,3,4,5")
Instead of what it should be:
SELECT * FROM `informations` WHERE 3 IN (1,2,3,4,5)
There is no automatic tokenisation (splitting on ,) performed; the one value of ids is not automatically converted into a list for you such that IN can work.
Unfortunately your table design has been your undoing here. Can you split the IDs into a separate table using the principle of database normalisation?
Then your query might look like:
SELECT * FROM `informations` WHERE 3 IN (
SELECT `id`
FROM `ids`
WHERE `informations`.`id` = `ids`.`information_id`
)
BTW, "information" is a non-countable noun and, as such, "informations" is wrong.
Update (thanks for the idea, a1ex07!)
Although this is hackery and I still suggest fixing your table layout, I'll be kind and suggest a quick fix.
Willempie was close with:
$query = 'SELECT *
FROM `informations`
WHERE `ids` LIKE "%' . $id . '%"';
Unfortunately, a wildcard match isn't quite powerful enough. Consider if ids is like "1,6,9,12,35,4" and $id is like 3. You get a false positive. The LIKE statement needs to be aware of the commas.
You can add multiple cases:
$query = 'SELECT *
FROM `informations`
WHERE `ids` LIKE "%,' . $id . ',%"
OR `ids` LIKE "%,' . $id . '"
OR `ids` LIKE "' . $id . ',%"';
Or, for brevity, you can work around this with regular expressions:
$query = 'SELECT *
FROM `informations`
WHERE `ids` REGEXP "(^|,)' . $id . '(,|$)"';
For any $id you wish to find, before it must be the start of ids (^) or a comma; after it must be a comma or the end of ids ($). This ensures that $id must be found as a whole, comma-delimited token.
It's a little like "Whole Word Only" in word processor searches, but with commas separating "words" instead of spaces.
Update 2
Another way uses FIND_IN_SET, which performs a search within a comma-delimited string:
$query = 'SELECT *
FROM `informations`
WHERE FIND_IN_SET("' . $id . '", `ids`)';
Your query is technically correct but the values for 'ids' are not.
You should enclose the values of ids within single quotes. If I were to write the code without using ids, it would be like this:
"SELECT * FROM informations WHERE ". $id ." IN ('1','2','3','4','5')"
More info on this rule here: http://dev.mysql.com/doc/refman/5.1/en/comparison-operators.html#function_in
I'm not sure what you are trying to achieve. If ids is a column in informations your code is just a weird way to express "SELECT * FROM informations WHERE ids = ". $id "; If it is a string, I don't see why you need WHERE at all : expression $id in (1,2,3,4,5) is constant, it doesn't require interaction with database; in any case you either grab all rows from informations or none.
UPDATE
Another suggestion :maybe ids is a string field in informations that contains "1,2,3,4,5". In this case you cannot get expected results by using WHERE ... IN. You need to use REGEXP to check if string contains your number.
It has to be column name then IN (comma separated values here).
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
You did an error in sql syntax.
This is the correct syntax
"SELECT * FROM informations WHERE ids IN (". $id .")";

Categories