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.
Do you have a variable $title_ or is it just $title?
If its just $title then:
$query = "select * from books where title like '".$title."_'";
LIKE, it should match any single character. so: $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.
addslashes is usually not a good idea at all... Poor escaping is worse than no escaping (since you think you're safe when you're not)...