在mysql LIKE中使用php变量

时间:2010-08-30 19:42:04

标签: php mysql

我想写一个像这样的mysql查询:

  

从书籍中选择*,标题如下   '$标题_';

$ title 是一个php变量。当我运行上面的查询时,它会抛出错误说

'$ title_ variable not found'

我怎样才能做到这一点?

谢谢..

8 个答案:

答案 0 :(得分:8)

使用:

"... WHERE title LIKE '". mysql_escape_real_string($title) ."_'";

您可以使用:

WHERE title LIKE '{$title}_'";

..但是有一个risk of SQL Injection attacks

答案 1 :(得分:4)

这样做:

$query = "select * from books where title like '{$title}_';"
$result = mysql_query($query) or die(mysql_error());

通过{}中的周围变量,您可以指定只有$title是变量,而不是_。双引号字符串将确保此变量扩展到其值。

答案 2 :(得分:0)

你有变量$ title_还是只是$ title?

如果只是$ title,那么:

$query = "select * from books where title like '".$title."_'";

答案 3 :(得分:0)

您的查询字符串必须如下所示:

$query  = "select * from books where title like '".$title."_'";

请注意,'".$title."_'

您收到的错误是因为您的查询正在使用$title而不是您的php变量的值$title

答案 4 :(得分:0)

尝试:

"select * from books where title like '{$title}_';"

大括号首先评估变量,然后将通配符_添加到变量值,从而为您的搜索条件提供sql查询。

答案 5 :(得分:0)

$ query =“select * from books where title like'”。 $ title_。“'”;

答案 6 :(得分:0)

$ query =“SELECT * FROM books WHERE title LIKE'”。$ title。“_';”;

答案 7 :(得分:-1)

mysql查询只是一个字符串。你只需要将$ title php变量的值放在这个字符串中。问题是此字符串后跟一个在变量名中有效的字符下划线,因此您必须分隔变量名称或下划线将包含在名称中。

有几种方法可以做到,例如:

$query = "select * from books where title like '${title}_'";
$query = "select * from books where title like '".$title."_'";

正如OMG Ponies所说,如果$ title来自某些用户输入,而不是来自程序的某些受控部分(例如,数据库中的另一个表),则该变量也应受到保护或存在SQL注入攻击的风险(执行多个查询,更具体地说是某个黑客准备的查询是一些有效的SQL。)

除了攻击之外,如果你不逃避,还有其他一些潜在的问题。想象一下,如果标题实际上包含引用,将会发生什么......

我通常会这样做:

$query = "select * from books where title like '".addslashes($title)."_'";

但是还有其他变种取决于逃避上下文以及您想要保护的内容。