简体   繁体   English

在MySQL中的select语句期间防止变量中的计算

[英]preventing calculations in variables during a select statement in MySQL

I'm trying to build a dynamic query based upon selections passed to a script. 我正在尝试根据传递给脚本的选择来构建动态查询。 Example: 例:

$qry = "SELECT * FROM machinekaart 
INNER JOIN afleveradressen ON afleveradressen.raaid = mkrraaid 
INNER JOIN kontaktpersonen ON kontaktpersonen.rkpraaid = mkrraaid   
WHERE mkrrid != '' " ;

if($_SESSION['oud'])
    $qry .= "  AND mkrvo < " . $cur_jaar_maand;

Field mkrvo is a text field, and can contain yyyy-mm besides other values. 字段mkrvo是一个文本字段,除其他值外还可以包含yyyy-mm。

eg when the varable $cur_maand_jaar contains '2015-01' the selection will be everything lower than 2014 例如,当变量$ cur_maand_jaar包含“ 2015-01”时,所选内容将低于2014

How can I stop this from happening and selecting everything lower than '2015-01' ?? 我该如何阻止这种情况的发生,并选择低于'2015-01'的所有内容?

I would suggest quoting that variable, so the values are taken literally: 我建议引用该变量,以便按字面值取值:

if($_SESSION['oud'])
    $qry .= "  AND mkrvo < '" . $cur_jaar_maand . "'";

Better than that, please use PDO so you can use bindings, it's safer and best optimized. 更好的是,请使用PDO,这样您就可以使用绑定了,它更加安全并且得到了最佳的优化。

Eg. 例如。

if($_SESSION['oud'])
    $qry .= "  AND mkrvo < ?";

// build your PDO Connection $myPdoConnection ...

$pdoStatement = $myPdoConnection->prepare($qry);

$pdoStatement->execute(array($cur_jaar_maand));

Within the SQL text, enclose the string literal in single quotes, so it's not evaluated as a numeric expression. 在SQL文本中,将字符串文字括在单引号中,因此不会将其评估为数字表达式。

Evaluated in a numeric context: 2015-01 produces a value of 2014 . 在数字上下文中评估: 2015-01产生的值为2014

But '2015-01' is evaluated as a string literal. 但是'2015-01'被评估为字符串文字。

(If the string literal is evaluated in a numeric context (eg '2015-01' + 0 ) the string will evaluate to a numeric value of 2015 .) (如果文字串在数值上下文进行评估(例如, '2015-01' + 0 )将字符串将评估为的数值2015 。)


The code you posted appears to be vulnerable to SQL Injection . 您发布的代码似乎容易受到SQL Injection的攻击。

Consider what SQL text is generated when $cur_jaar_maand happens to evaluate to 0 OR 1=1 -- . 考虑一下$cur_jaar_maand恰好求值为0 OR 1=1 --时生成的SQL文本。

A much better pattern is to make use of prepared statements with bind placeholders . 更好的模式是使用带有绑定占位符的预 准备语句

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM