开发者

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 que开发者_JAVA技巧ry, 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜