apostrophes are breaking my mysql query in PHP - php

My database has name records that occasionally contain apostrophes, such as Joe's Bar and I've just coded a query script in PHP that grabs that field and sticks it into a select statement with the usual $query = "SELECT address FROM restaurants WHERE name='$name'"; and the apostrophe in some of the restaurant names derails the Love Train.
How do I keep this from happening?
Snide answer - Use the same technique you used when you inserted them INTO the database via PHP.
Rebuttal - I was having the same problem then and cheated and entered the troublesome ones directly using PHPMyAdmin but this can't be ignored any longer.
Thank you for taking the time to answer this during the holidays.

You have to $name = mysql_real_escape_string($name); before that line.
You might also want to read up on SQL Injections, since your inputs are clearly unsanitized.

Have a look here
How can I use an apostrophe (') in a
query string?
mysql_real_escape_string
PHP mysql_real_escape_string

Related

Error updating record: Unknown column 'Jason' in 'field list'

Forgive me if this already exists, but I didn't see anything close enough to my issue to offer any kind of solution or path toward solving.
My Query:
$sql = "UPDATE users SET FirstName=$fname WHERE id=$id";
$fname does equal Jason. But it should be changing the sql field FirstName to "Jason". Instead, it is trying to find a field named Jason. I have tried hardcoding in "Jason", but then it says that there is an unexpected string. Hardcoding it in would actually cause issues as the data needs to be a variable so the user can change to their First Name to whatever they want. I have echo'd $id and that value is coming across correctly. My code is in php.
Long time reader of stackoverflow.com, first time poster. If there is any additional code or info that might be helpful, please let me know.
EDIT: I had not realized that variables also need to be within quotes. I assumed the quotes were specifically for hardcoded strings. Placing $fname within single quotes as '$fname' solved it. Thank you, everyone!!!
Use single quotations:
$sql = "UPDATE users SET FirstName='$fname' WHERE id=$id";
Be sure about securing your SQL query; if the $fname's value is dynamic, then you must escape special characters using mysqli_real_escape_string to avoid a very dangerous vulnerability SQL Injection.

php & mysql search query escape

I have a movie database website and I'm having a small issue with the search.
Lets say that the movie name saved in the database is
Going Clear: Scientology and the Prison of Belief
As you can see there a : in the title.
When my users search for Going Clear Scientology and the Prison of Belief they get no results, same if the movie title has ', here is my search query:
SELECT * FROM movie WHERE title LIKE '%$search%'
How can I fix that?
Keep two things in mind when trying to insert into the database using php.
First, when you are inserting into the database your data, say for example the movie name here "Going Clear: Scientology and the Prison of Belief", trim off the extra strings like : . This well help you later on.
Second, similar to the first one, when you are taking an input from the user sanitize it. There might be strings like ',$,\,? etc which are not relevant. After you have done that you can go for a query search in the DB.
I guess your code here is okay.
select * from movie where title like 'Going%';
The above query works for me when I check it in my DB. See if your search variable is initializing properly.
You need to escapes special characters in a string for use in an SQL statement. Always store these type of value into database after escaping special character and also pass your search term into query after escaping special character.
For this you have to use
mysql_real_escape_string()
Eg:
$search = "Going Clear: Scientology and the Prison of Belief";
$search = mysql_real_escape_string($search);
$query= "SELECT * FROM movie WHERE title LIKE '%$search%'";
You can read here
http://php.net/manual/en/function.mysql-real-escape-string.php

MySQL Escaping Needed After Inserting Data

Do I need to use mysqli_real_escape_string when reusing data from a database for a query. The data was previously escaped so it can be safely inserted into the database. I am aware that when inserting data into a database, backslashes are removed.
Thanks.
Yes, you have to re-escape data that came from a DB when you're re-using it in another query. Consider escaping to be the equivalent of gift wrapping on a present. You "wrap" some data for the database in one query. It'll UNWRAP the data and put it in the data store. When you retrieve that data again later, the wrapping's gone and the data's "dangerous" again.
e.g. consider something like this:
$name = "Miles O'Brien";
$safe = mysql_real_escape_string($name); // name becomes Miles O\'Brien
$sql = "INSERT INTO people (names) VALUES '$safe'";
$result = mysql_query($sql) or die(mysql_error());
Now that name's in the database, but the escaping you performed is NOT PRESENT anymore - it was removed by the database as it processed the query, so if you do something like this:
$sql = "SELECT name FROM people"
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_asssoc($result)) {
$name = $row['name']; // get Miles O'Brien from the DB again
here you'll literally have retrieved Miles O'Brien with no escaping at all.
$other_sql = "UPDATE ... WHERE name=$name"; <---INJECTION HERE
}
Escaping is not something you do only with "outside" data... ANY data you insert into a query string is "outside" data, even if you just got that data from the database just a few lines of code ago.
TL;DR: You can easily inject yourself.
Yes, you need it. The escapes are only used to make the query syntactically valid, they're not part of the data that's stored in the table. Any time you're interpolating strings into a query, you need to escape it.
As an example, suppose you have a table of full names, and there's someone with the last name O'Reilly. You perform a query to get this name into $lname, and then you want to use that variable in another query, e.g.
$query = "SELECT username WHERE last_name = '$lname'";
If you don't escape the string, the resulting query will be:
SELECT username WHERE last_name = 'O'Reilly'
As you can see, the quotes are not properly balanced. You need to escape it so that it will be:
SELECT username WHERE last_name = 'O\'Reilly'
However, if you use prepared queries with placeholders for these parameters, you don't need to worry about this much at all (in fact, it would be wrong to escape a variable that's bound to a placeholder, as you will then store the backslashes). This is generally preferred.
Also, consider NOT extracting and re-storing the data at all, but moving data around using SQL itself:
INSERT INTO Table1 (last_name)
SELECT last_name
FROM Table2
WHERE ...
This is also likely to be more efficient, since the data doesn't have to move between the database and the application.
That's not what escaping means.
Escaping text means inserting escape characters so that it can be inserted into a SQL string and be interpreted as the original text.
It has no effect on the actual value, unless you use the wrong escape characters.
You need to correctly escape your text every time you concatenate it into any kind of structured language.
When using SQL, you should ideally use parameters instead of concatenation.
There are a lot of misunderstanding on the topic.
People keep using improper words, and a real danger coming from such a confusion.
escaping being confused with safety
data being confused with strings
formatting being confused with trusting
One have to sort these matters out.
Otherwise we still have an accepted answer implying that using mysql_real_escape_string does produce a "safe" variable. While it is not.
Just remember to validate properly all user inputted data that you plan on using and don't allow html or javascript code to be inserted. You also need to keep in mind XSS attacks, not just MySQL Injections. A good way to prevent xss is using htmlspecialchars() to convert HTML characters into HTML entities.

PHP mysql_real_escape_string is not working as expected

I have a weird problem.
I have a table which has a title field.
I am inserting values into this title field using mysql_real_escape_string. Inserting is working fine for values with single quotes.
Some other place I am doing a select using title filed in the where clause as below
SELECT * FROM table WHERE title=mysql_real_escape_string(Girish's Photo);
This query is returning empty result set even when I inserted Girish's Photo.
---- Editing to put some code
$photo_title=mysql_real_escape_string($_POST[photo_title]);<br/>
$sql = "INSERT INTO photos values($id,'$photo_title');<br/>
using this from a form I have inserted Girish's Photo into photo_title. It worked fine.
...
..
..
Then at some other place in PHP
$title="Girish's Photo";
$sql = "SELECT photo_id,photo_title FROM photos WHERE photo_title ='" . mysql_real_escape_string($title)."'" ;
But this query is returning empty result set.
Using phpMyAdmin, if I try to run the above query .. the result is empty. If I browse the table I see value Girish\'s Photo
Now if I run the query on phpMyAdmin replacing where clause with where photo_title='Girish\''s Photo' I am getting the record.
$data = "Girish's Photo";
$query = "SELECT * FROM table WHERE title='".mysql_real_escape_string($data)."'";
mysql_real_escape_string() is a PHP-function, which should be used as follow:
"SELECT * FROM table WHERE title='".mysql_real_escape_string("Girish's Photo")."'";
However, this is bad practice.
Okay so you're going to want to use PDO for all queries. Primarily for the following reasons:
mysql_* is being deprecated.
It's not safe from SQL Injection.
PDO is capable of accessing numerous database engines making it much more flexible without changing the API.
Please take a look at this post to get a look at how to issue a SELECT using PDO.
Parameterized SELECT queries via PDO?
I had a similar problem recently which I solved by using htmlentites() instead of mysql_real_escape_string() check it out in the manual or w3 schools
EDIT: this is a valid answer because he's using mysql_real_escape_string() in the wrong context in the first place. if you read the question, he's escaping a FILENAME and therefore he's not at risk of injection. If you're going to downvote at least say why..
The value in your database should not contain backslashes. That's why your query doesn't match. Girish's Photo does not match Girish\'s Photo. Sounds like you are a victim of magic quotes. Read the manual and get rid of them.

Trouble with LIKE MySQL query

I have the following MySQL query that I execute from a .php page
SELECT * FROM servers WHERE name LIKE '%$value%'
which, when executed, selects 0 rows (However, the query runs successfully, so I can't use mysql_error() to debug). When I run the query in PHPMyAdmin it selects the appropriate rows. Other queries such as
SELECT * FROM servers
work fine. I can put my code up here if it will help.
Edit: Here's something offering an improvement based on Marek's answer below. Please see the comments regarding the practice of putting variables directly into queries and consider using prepared statements. Anyway, here it goes.
PHP substitutes variables inside doubly-quoted strings, but not inside singly-quoted strings.
One quote character is just treated as an ordinary character within a string delimited by the other.
Putting that together, you can write:
$q = "SELECT * FROM servers WHERE name LIKE '%$value%'"; //Fine
You cannot write:
$p = 'SELECT * FROM servers WHERE name LIKE "%$value%"'; //Broken!
$q works because it's a doubly-quoted string, and the apostrophes are just ordinary characters. $p does not work because it's a singly-quoted string.
As pointed out by GoodFather below, you can also say ${value} to avoid ambiguities with the ambient string, e.g. $r = "ABC${value}DEF";.
You really need to look at doing this query more safely. This will help with your issue as well. As it stands, you are vulnerable to SQL injection. Look at the examples from the PHP manual for how to do it right:
http://php.net/manual/en/function.mysql-query.php
EDIT: From your comments you mentioned that you are already taking care of the string properly, which is great. The code below should fix your problem.
For example, you could rewrite your query statement (in PHP) like so:
$query = sprintf("SELECT * FROM servers WHERE name LIKE '%". mysql_real_escape_string($value) . "%'");
That will clean up your code and it will also handle the issue with your LIKE statement not working properly.
Here is another good article on the subject:
http://joshhighland.com/blog/2008/07/06/php-sprintf-sql-like/
Are you expecting a case-sensitive or case-insensitive query? I'm betting case-insensitive since you're expecting results but not seeing them. Take a look at your database's default collation or the table's specific collation and make sure it ends in _ci, whatever it is.

Categories