What's wrong in this simple PHP SQL sentence? - php

i want to recober all the users with "blo" in their full name, for example: "Pablo"
I pass the "blo" parameter with user PHP parameter:
$q=mysql_query("select * From user Where fullName Like '%'".$_REQUEST['user']."'%'",$link );
something is wrong in the php SQL sentence, because when i try the sentence with the argument "blo" on my SQL database, i see that the SQL sentence is correct, because it returns me correct result, this is the sentence with the argument "blo" on it: select * From user Where fullName Like "%blo%"
i'm sure that the PHP is receiven the "blo" parameter correctly, then, it have to be a sintax error of the SQL sentence on the PHP.... but i can't find it
EDIT : OK!! the last sentence is solved, but now i have this new sentence with the same problem, it have a error but i dont know where
$query = sprintf("SELECT u.*
FROM USER u
WHERE u.fullName LIKE '%%%s%%' AND email NOT IN (select pp.fk_email2 from permission pp where pp.fk_email1='".mysql_escape($_REQUEST['mymail'])."') AND email NOT LIKE '".mysql_escape($_REQUEST['mymail'])."' ",
mysql_real_escape_string($_REQUEST['user']));

SQL requires single quotes to indicate a string for comparison, and the wildcard character (%) must be included inside of those single quotes. Double quotes are used for column and table aliasing only, if at all.
$query = sprintf("SELECT u.*
FROM USER u
WHERE u.fullName LIKE '%%%s%%'",
mysql_real_escape_string($_REQUEST['user']));
$q = mysql_query($query, $link);
Secondly, you're leaving yourself open to a SQL injection attack by not sanitizing the user request variable. Always use mysql_real_escape_string when dealing with strings being submitted to a MySQL database.

You have the quotes messed up. use this:
$q=mysql_query('SELECT *
FROM user
WHERE fullName LIKE "%' . $_REQUEST['user'] . '%"',$link );
BTW, this is bad practice. You are using un-escaped input in your query and are open to SQL injection.

It looks like your quotes are off.. try something like...
$q=mysql_query("select * From user Where fullName Like '%".$_REQUEST['user']."%'",$link);
Also, you will want to make sure that the incoming param is sql-escaped to prevent sql injection. I don't know php, but it's probably something similar to...
$q=mysql_query("select * From user Where fullName Like '%".mysql_escape($_REQUEST['user'])."%'",$link);

I think it must be ... Where fullname like '%" . $_REQUEST['user']."%'"...
with the % symbol inside the simple quotes.

#AndroidUser99: Change the query to --
$q = mysql_query("select * from user Where fullName like '%" . $_REQUEST['user'] . "%'", $link);
Update
I think we may need more code since none of the answers seem to be 'working'. Is the database link even being instantiated in $link? If there are errors what are they?

Related

sql returning no results

The following code is returning no results where I use the variable in the code of $dep if I manually put the value in of 1 it returns the expected result. I have tried it with no quotes single quotes and double quotes. I have looked though loads of examples and I cannot see what I am doing wrong
$dep = 1;
if (!$names) {
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM '.TOPIC_TABLE
. ' WHERE dept_id='$dep' ORDER BY `sort`";
$res = db_query($sql);
I'm pretty sure your error is related to wrong quotes used.
In your code, you write
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM '.TOPIC_TABLE
. ' WHERE dept_id='$dep' ORDER BY `sort`";
After FROM, you are using single-quotes('), but your whole query has been enclosed into double-quotes("), so that creates the issue.
It should be:
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM ".TOPIC_TABLE
. " WHERE dept_id='$dep' ORDER BY `sort`";
EDIT: Forgot to point out you should seriously use PDO or any other SQL Injection prevention methods. If, under any circumstance, your $dep variable could be sent via a public form, you could end up by having your DB dumped in the best case.
There's a syntax error in the second line of the query - if you want single-quotes in the query, then you need to enclose it all in double-quotes:
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM ' .TOPIC_TABLE
. " WHERE dept_id='$dep' ORDER BY `sort`";
By the way, building a query like this, using string concatenation, is a REALLY BAD IDEA and leaves you open to SQL injection attacks - you should use prepared statements and parameters instead.
First as Fred -ii says make sure the if statement is executing properly. Then if dept_id is an integer value then you should not need the single quotes as scaisEdge says. Otherrwise the SQL looks fine. Make sure that there are in deed records in the database for the dept_id that is being passed in.

SQL Wildecard Query in PHP

I'm trying to create a restaurant search that will find the restaurant in the database even when the user only inputs part of the whole name.
Here is the code:
First I take the input, sanitize it and then add the % signs to the left and right.
$restaurantNameTest = InputCleaner($_GET["restaurantName"]);
$restaurantName = ('%' . $restaurantNameTest . '%');
Then I run the query:
$result = mysqli_query($conn,
"SELECT restaurantID,restaurant_name, cusine, wait_time
FROM Restaurant
WHERE restaurant_name = '$restaurantName'");
For some reason this isn't working and no results are found unless I type in the name perfectly. Am I doing it wrong?
Use Like instead
$result = mysqli_query($conn,
"SELECT restaurantID,restaurant_name, cusine, wait_time
FROM Restaurant
WHERE restaurant_name LIKE '$restaurantName'");
This is more of an SQL question than a PHP question, but what I believe you need is the LIKE comparison of the WHERE clause.
So change your query to read: ...WHERE restaurant_name LIKE '$restaurantName'");
LIKE will match partial strings, based on the placement of the wildcard (%) character(s).
So a few things to note, first of all to echo what others have said -- you should be using LIKE in your query. On top of that you should really be using MySQLi's prepared statements
So you will want a your code to look something like this:
$sql = "SELECT restaurantID,
restaurant_name,
cusine,
wait_time
FROM Restaurant
WHERE restaurant_name LIKE '%?%'";
$query = $connection->prepare($sql);
$query->bind_param('s'. $restaurantName);
$query->execute();
I'm primarily a PDO user so you may want to double check the above syntax, but it should work.
To re-iterate on your question specifically:
Use LIKE with your wildcards to get the result you're after and not =.

Escaping quotes and percentage sign in SQL

I checked similar questions but couldn't find any solution to my particular problem. I have a PHP method that I use as follows:
SELECT * FROM login WHERE userID = 10 //To get this
$result = query("SELECT * FROM login WHERE userID = '%d' ", $userID) //I use this
so the character set '%d' is replaced by what I post in the $userID and the result is returned as JSON. Now i am trying to use it for a search function using.
select * from login where userName like '%searchString%' //Now to get this
$result = query("SELECT * FROM login WHERE userName LIKE '%'%s'%'", $username) // I am trying this
However I got error probably due to not escaping strings properly. Is it possible for any of you to solve this with given information?
Thanks
arda
You also need to change the where clause to use LIKE instead of =
$result = query("select * from login where userName like '%%s%'", $username)
I'm assuming your query method will search/replace the %s with the value of $username.One thing to be mindful is that using "select *" results in an inefficient query execution plan, you should change the * to a list of the columns from the table you want to retrieve. Also, be mindful of SQL injection attacks. See this link http://en.wikipedia.org/wiki/SQL_injection.
you may try by changing this '%'%s'%'
select * from login where userName like '%searchString%' //Now to get this
$username=mysql_real_escape_string($username);
$result = query("SELECT * FROM login WHERE userName = '%%s%'", $username) // I am trying this
I found the solution to be easier than I thought. I simply passed %searchString% as an argument instead of plain searchString
Escaping quotes and escaping percentage signs are two different matters.
First the quotes. The bad way is to "quote the quotes", ie replace all single quotes with two single quotes. It works, but there are disadvantages. The better way is to use query parameters. I don't work with php so I don't know all the details, but I read a lot of comments and answers here on StackOverflow telling php users to use prepared statements. They may or may not escape quotes. My guess is that they do.
For percentage signs, you have to surround them with square brackets to keep them from being treated as wild cards. For example, if your where clause is:
where somefield like '75%'
and you want it to return
75% of bus passengers like singing
but not return
75 bottles of beer on the wall
then your where clause has to be:
where somefield like '75[%]%'

How can i check name with single quotes in SQL?

I have used below code for checking lastname(case sensitive) from DB.
SELECT * FROM BL12_anncurtis_existing_customers WHERE BINARY LastName LIKE 'ravi'
Its work fine. But, it does not work when the name like below, I passes this last name using php variable($lname).
SELECT * FROM $table_name WHERE BINARY LastName LIKE '$last_name'
SELECT * FROM BL12_anncurtis_existing_customers WHERE BINARY LastName LIKE 'O'Connor'
How can I resolve this?.
You need to escape all single quotes with a single quote:
SELECT * FROM BL12_anncurtis_existing_customers WHERE BINARY LastName LIKE 'O''Connor'
this should work.
SELECT * FROM BL12_anncurtis_existing_customers WHERE BINARY LastName LIKE 'O\'Connor'
and for php of course, you have mysql_escape or all PDO prepared statements that will take care of this automatically , given the LIKE value you use is bound to a php variable.
When you're building the query in your PHP script, use the addslashes function on the value you are searching for:
$query = "SELECT * FROM BL12_anncurtis_existing_customers WHERE BINARY LastName LIKE '" . addslashes($name) . "'"
This will escape any characters that need it and will produce the result you are looking for.
Another solution is to use double quotes in the query instead of single quote:
SELECT * FROM BL12_anncurtis_existing_customers WHERE BINARY LastName LIKE "O'Connor"
but I think I prefer the first solution
you can write yourself a little program which uses regex for matching quotes, the program can validate and fix mistakes made by user.
You should be escaping your string with mysql_real_escape_string()
if you have magic_quotes_gpc turned on (which you should know is a bad idea). This means that strings gathered from $_GET, $_POST and $_COOKIES are escaped for you (i.e., "O'Connor" -> "O\'Connor").
Once you store the data, and subsequently retrieve it again, the string you get back from the database will not be automatically escaped for you. You'll get back "O'Connor". So, you will need to pass it through mysql_real_escape_string()
SELECT * FROM sometable where LastName LIKE '%''%'
WHERE BINARY LastName LIKE "O'Connor"
this works for me
I think that the \' may be better, but both work

using php variable in mysql LIKE

I want to write a mysql query something like this:
select * from books where title like
'$title_';
The $title is a php variable. when i run the above query, it throws an error saying
'$title_ variable not found'
How can I achieve this?
Thanks..
Use:
"... WHERE title LIKE '". mysql_escape_real_string($title) ."_'";
You could use:
WHERE title LIKE '{$title}_'";
..but there's a risk of SQL Injection attacks
Do it like this:
$query = "select * from books where title like '{$title}_';"
$result = mysql_query($query) or die(mysql_error());
By surrounding variable in {} you can specify that only $title is a variable and not the _. And the double-quote string will ensure that this variable gets expanded to its value.
Your query string must looks like:
$query = "select * from books where title like '".$title."_'";
Please note, the '".$title."_'
The error you are getting is because your query is taking $title and not the value of your php variable $title
Try:
"select * from books where title like '{$title}_';"
The curly braces first evaluate the variable and later add your wildcard _ to the variable value thereby providing sql query with your search criteria.
$query = "select * from books where title like '" . $title_ ."'";
$query = "SELECT * FROM books WHERE title LIKE '".$title."_';";
Do you have a variable $title_ or is it just $title?
If its just $title then:
$query = "select * from books where title like '".$title."_'";
The mysql query is merely a string. You just have to put the value of your $title php variable inside this string. The problem is that this string is followed by a character underscore that is valid in a variable name, hence you have to delimit the variable name or underscore will be included in the name.
There is several way to do it, for exemple:
$query = "select * from books where title like '${title}_'";
$query = "select * from books where title like '".$title."_'";
As OMG Ponies said, if $title came from some user input and not from some controlled part of your program (for exemple another table in database), the variable should also be protected or there is some risks of SQL injection attack (executing more than one query, and more specifically a query prepared by some hacker to be some valid SQL).
Beside attacks, there is also some other potential problems if you do not escape. Imagine what will happen for exemple if the title actually contains a quote...
I would usually do:
$query = "select * from books where title like '".addslashes($title)."_'";
but there is other variants depending the escaping context and what you want to protect from.

Categories