SQL statements where value could be nothing (empty) - php

I have some search functionality which allows a user to either select a name from a drop down list or type a persons name or part of it (wildcard functionality) into a search field.
The problem I am having is that if the drop down option is used then the search field won't be and vice versa.
I have tried some SQL as follows (please note the variables represent data sent in via a form):
SELECT id, name, age FROM player
WHERE player.id = '$id'
OR player.name LIKE '%$text%'
When the above is used the wildcard functionality works fine.
However if you select a player from the drop down then it returns all players. This is because the value for $text is nothing (empty) and LIKE '%%' means select everything and hence it selects all names.
I then tried the following:
SELECT id, name, age FROM player
WHERE player.id = '$id'
AND player.name LIKE '%$text%'
Now the drop down functionality works as expected but wild card searches do not work. This is because I assume that AND requires both statements to be true and because $id is nothing (empty) when just a wildcard entry is specified, the condition is never true.
Can anyone help me with some sql to ensure that both the dropdown and the wildcard search work in isolation of each other?
Thanks for your time and help in advance.

$params = ''
if($id !== ''){
$params = "player.id = '$id'";
} else if($text !== ''){
$params = "player.name LIKE '%$text%'";
}
$sql = "SELECT id,name,age FROM player WHERE {$params}";
mysql_query($sql); //if using mysql_

Require id conditionally:
$idCondition = "";
if ($id) {
$idCondition = "player.id = '$id' AND ";
}
$query = "SELECT id, name, age FROM player WHERE {$idCondition}player.name LIKE '%$text%'";

"SELECT id, name, age FROM player
WHERE (player.id = '$id' AND '$id' <> '')
OR (player.name LIKE '%$text%' AND '$text' <>'')"

Related

What is the correct MySQL syntax to retrieve data with multiple parameters

I am retrieving data from a database with php and MySQL as follows
$query = mysql_query("SELECT * FROM pictures WHERE (title LIKE '%$Search%' OR keywords LIKE '%$Search%') AND approved = 'YES' ORDER BY title ASC");
The query is correct and there are no errors and the query works fine for "title LIKE '%$Search%'" but the parameter "OR keywords LIKE '%$Search%'" is not retrieving data. The parameter "AND" also works correctly.
The keywords are stored in the database for example "pizza, restaurants, take away" but I don't see that is a problem.
My question is "What is the correct syntax for applying the "OR" parameter?
Remove the brackets around (title LIKE '%$Search%' OR keywords LIKE '%$Search%')
Those are generally used for subqueries.
$query = mysql_query("
SELECT * FROM pictures
WHERE title LIKE '%$Search%'
OR keywords LIKE '%$Search%'
AND approved = 'YES'
ORDER BY title ASC
");
https://dev.mysql.com/doc/refman/5.0/en/subqueries.html
Here is an example of a subquery, and pulled from the manual on MySQL.com:
SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);
Edit:
Or try a different quoting method:
$query = mysql_query("
SELECT * FROM pictures
WHERE title LIKE '".%$Search%."'
OR keywords LIKE '".%$Search%."'
AND approved = 'YES'
ORDER BY title ASC
");
You could also try escaping your data:
$Search = mysql_real_escape_string($Search);
as an example. I don't know how you're assigning that variable.
phpMyAdmin test edit:
This is what I used inside phpMyAdmin:
SELECT * FROM table
WHERE col1 LIKE '%pizza%'
OR col2 LIKE '%pizza%'
AND col3 = 'YES'
ORDER BY col1 ASC
using pizza as the search keyword seeing that $Search will be based on the same keyword for you, where columns contain "large pizza" in one, and "pizza, take away, restaurants" in another.
Remember that, whatever you're using/assigning $Search to, must reside inside all your queried columns.
You may also want to make use of explode().
Here is an example pulled from https://stackoverflow.com/a/15289777/
<?php
$search = 'Gold Chain Shirt';
$bits = explode(' ', $search);
$sql = "SELECT name FROM product WHERE name LIKE '%" . implode("%' OR name LIKE '%", $bits) . "%'";
The above will generate this query:
SELECT name FROM product WHERE name LIKE '%Gold%' OR name LIKE '%Chain%' OR name LIKE '%Shirt%'
Sorry for taking some time but this is my working answer to my own question... not the prettiest syntax but it works without any string functions or explode functions. MySql can handle keywords quite well without any other functions being included:
$query = mysql_query("SELECT * FROM pictures
WHERE
title LIKE '%$Search%' AND featured IS NOT NULL AND streetview IS NOT NULL AND (id_user > '1') AND (status = '1')
OR
keywords LIKE '%$Search%' AND featured IS NOT NULL AND streetview IS NOT NULL AND (id_user > '1') AND (status = '1') ORDER BY title ASC");
Thank you all for your contributions

SQL "LIKE" If empty returns all rows

Hello I have 2 textboxes and i want to give to the user the option to choose one in order to find results. The user can search through the id or the name. My problem is because i use LIKE%field% when the user chooses to search through the id the name field stays empty and returns all the table rows. I want to have results only if the user enters some value in the textbox. This is my sql query. I'm using mysql
"SELECT * FROM properties WHERE ID='$id' OR Name LIKE '%$name%'"
Thank you all
If the user has to select which field to search, you can do:
if ($_POST['search'] == 'id') {
$sql = "SELECT * FROM properties WHERE ID='$id'"
} else {
$sql = "SELECT * FROM properties WHERE Name LIKE '%$name%'"
}
You can do this in a single query (values are checked from the query itself):
"SELECT * FROM properties WHERE ('$id'='' OR ID='$id') AND ('$name' ='' OR Name LIKE '%$name%')"
Explanation:
First condition:
The query will select records with ID='$id' only when $id is not empty.
If $id is empty, query will not go for the second part ID='$id'
Second condition:
The query filters records with Name LIKE '%$name%' only when $name is not empty.
If $name is empty, query will not go for Name LIKE '%$name%'.
NB: This technique is extremely useful when you have numerous parameters to check, rather than using a bunch of if...elses at php side.

PHP PDO result from query

I am trying to do a query in PHP PDO where it will grab a simple result. So like in my query I need it to find the row where the column group is 'Admin' and show what ever is in the group column. I know that we already know what it should be [Should be admin] but just need to get the query to work. Its only grabbing 1 row from my table, so will I need forsearch?
If I change WHERE group = 'Admin' to WHERE id = '1' it works fine. But I need it so it can be where group = 'admin'
$sql2 = "SELECT * FROM groups WHERE group = 'Admin'";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$users2 = $stm2->fetchAll();
foreach ($users2 as $row2) {
print ' '. $row2["group"] .' ';
}
Thanks
group is a reserved word in MySQL, that's why it's not working. In general it's a bad idea to use reserved words for your column and table names.
Try using backticks around group in your query to get around this, so:
$sql2 = "SELECT * FROM groups WHERE `group` = 'Admin'";
Also you should really use placeholders for values, because you're already using prepared statement it's a small change.
Edit: just to clarify my last remark about the placeholders. I mean something like this:
$sql2 = "SELECT * FROM groups WHERE `group` = ?";
$stm2->execute(array('Admin'));
try to use wildcard in your WHERE Clause:
$sql2 = "SELECT * FROM groups WHERE group LIKE '%Admin%'";
Since the value in your table is not really Admin but Administrator then using LIKE and wildcard would search the records which contains admin.

MySQL PHP Query placed within another query's while loop failing

I have a column of pony names, where the breeder's Prefix is included with the pony's name (eg. Ashbrook Boy, where Ashbrook is the Breeder's Prefix, and Boy is the name of the pony). I have another table where I have a list of all the Prefixes used. I want to cycle through that list, and for each record search through my ponies and fetch those whose names begin with each prefix in turn. When they are fetched, I want to remove the said prefix from their name, and pop it into a column for that purpose on their own table.
In the end, I want -rather than one column with both Prefix and Name mixed in - two columns: one for Prefix, one for Name.
I thought the code below would do it for me, but it's not working. I get a 'not a valid resource' error for $res. Any help you could give me would be hugely appreciated - I really don't want to do this by hand! :P
I'm using a PHP script off a MySQL db, which I can access via PHPMyAdmin.
include '../conn.php';
$q=mysql_query("SELECT DISTINCT Pre FROM prefixes");
while($r=mysql_fetch_array($q)) {
$pre=$r['Pre'];
$sql="SELECT ID, Name FROM profiles WHERE (Name REGEXP '^$pre') ORDER BY ID ASC";
mysql_query($sql);
echo $sql;
while($res=mysql_fetch_array($sql)){
$name=$res['Name'];
$name=trim(str_replace("$pre","", $name));
$id=$res['ID'];
mysql_query("UPDATE profiles SET Prefix = '$pre', Name = '$name' WHERE ID = '$id' ");
}
}
mysql_close($con);
Your mistake come from the fact that $sql is the query string, not the mysql result of the query
$sql="SELECT ID, Name FROM profiles WHERE (Name REGEXP '^$pre') ORDER BY ID ASC";
mysql_query($sql);
echo $sql;
while($res=mysql_fetch_array($sql)){
with this, it will look better :
$sql="SELECT ID, Name FROM profiles WHERE (Name REGEXP '^$pre') ORDER BY ID ASC";
$result = mysql_query($sql);
while($res=mysql_fetch_array($result)){

mysql like statement is not working as expected

I have a table with 4 record.
Records: 1) arup Sarma
2) Mitali Sarma
3) Nisha
4) haren Sarma
And I used the below SQL statement to get records from a search box.
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%$q' LIMIT 5";
But this retrieve all records from the table. Even if I type a non-existence word (eg.: hgasd or anything), it shows all the 4 record above. Where is the problem ? plz any advice..
This is my full code:
$q = ucwords(addslashes($_POST['q']));
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%".$q."' LIMIT 5";
$rsd = mysql_query($sql);
Your query is fine. Your problem is that $q does not have any value or you are appending the value incorrectly to your query, so you are effectively doing:
"SELECT id,name FROM ".user_table." WHERE name LIKE '%' LIMIT 5";
Use the following code to
A - Prevent SQL-injection
B - Prevent like with an empty $q
//$q = ucwords(addslashes($_POST['q']));
//Addslashes does not work to prevent SQL-injection!
$q = mysql_real_escape_string($_POST['q']);
if (isset($q)) {
$sql = "SELECT id,name FROM user_table WHERE name LIKE '%$q'
ORDER BY id DESC
LIMIT 5 OFFSET 0";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "id: ".htmlentities($row['id']);
echo "name: ".htmlentities($row['name']);
}
} else { //$q is empty, handle the error }
A few comments on the code.
If you are not using PDO, but mysql instead, only mysql_real_escape_string will protect you from SQL-injection, nothing else will.
Always surround any $vars you inject into the code with single ' quotes. If you don't the escaping will not work and syntax error will hit you.
You can test an var with isset to see if it's filled.
Why are you concatenating the tablename? Just put the name of the table in the string as usual.
If you only select a few rows, you really need an order by clause so the outcome will not be random, here I've order the newest id, assuming id is an auto_increment field, newer id's will represent newer users.
If you echo data from the database, you need to escape that using htmlentities to prevent XSS security holes.
In mysql, like operator use '$' regex to represent end of any string.. and '%' is for beginning.. so any string will fall under this regex, that's why it returms all records.
Please refer to http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html once. Hope, this will help you.

Categories