在查询中使用PHP变量 [英] Using PHP variable inside a query

查看:83
本文介绍了在查询中使用PHP变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 PHP 内使用以下查询:

 $query =  'SELECT * from #__chronoforms_UploadAuthor where text_6 like "%'.$_GET['title'].'%" and text_7 like "%'.$_GET['author'].'%" limit 0,1';

我要在其中插入PHP变量而不是1的限制。.

Where I am trying to insert a PHP variable instead of 1 in the limit..

   $query =  'SELECT * from #__chronoforms_UploadAuthor where text_6 like "%'.$_GET['title'].'%" and text_7 like "%'.$_GET['author'].'%" limit 0,"'.$_GET['limit'].'"';

但这显示了一个错误。保留 $ _ GET ['limit'] 有一些错误。

but it shows me an error. There are some errors in keeping $_GET['limit'].

推荐答案

三件事:


  1. 编写这些查询的方式有点难以理解。我个人更喜欢使用多行 heredoc 语法(如下所示),但这不是严格要求;

  1. The way you're writing out those queries is a bit hard to read. Personally I prefer using a multi-line heredoc syntax (as per below), but this isn't strictly required;

任何用户输入都应通过 mysql_real_escape_string() 以避免 SQL注入攻击。 注意:用户输入包括来自客户端的任何内容,包括cookie,表单字段(普通或隐藏),查询字符串等;和

Any user input should go through mysql_real_escape_string() to avoid SQL injection attacks. Note: "user input" includes anything that comes from the client including cookies, form fields (normal or hidden), query strings, etc.; and

您不需要在 LIMIT 子句中引用第二个参数,这可能是问题的根源,即放 LIMIT 0,5 而不是 LIMIT 0, 5

You don't need to quote the second argument to LIMIT clause, which is probably the source of your problem, meaning put LIMIT 0,5 not LIMIT 0,"5".

所以尝试:

$title = mysql_real_escape_string($_GET['title']);
$author = mysql_real_escape_string($_GET['author']);
$limit = (int)$_GET['limit'];

$query = <<<END
SELECT *
FROM #__chronoforms_UploadAuthor
WHERE text_6 LIKE "$title%" 
AND text_7 LIKE "%$author%"
LIMIT 0,$limit
END;

此外,一位评论员指出, _ 应该转义。这可能是正确的,也可能不是。许多应用程序允许用户输入通配符。如果是这种情况,那么您就不应逃避它们。如果必须转义它们,则对其进行处理:

Also, one commentor noted that % and _ should be escaped. That may or may not be true. Many applications allow the user to enter wildcards. If that's the case then you shouldn't escape them. If you must escape them then process them:

$title = like_escape($limit);

function like_escape($str) {
    return preg_replace('!(?|\\)((?:\\)*)([%_])!', '$1\$2', $str);
}

这种有点复杂的正则表达式试图阻止某人输入'\% ',并获得'\%',然后转义反斜杠而不是'%'。

That somewhat complicated regular expression is trying to stop someone putting in '\%' and getting '\%', which then escape the backslash but not the '%'.

这篇关于在查询中使用PHP变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆