简体   繁体   English

基本PHP-SQL查询中的条件串联

[英]Basic PHP - Conditional Concatenation Within SQL Query

I'm having some trouble with what I believe should be some fairly simple PHP. 我觉得应该是一些相当简单的PHP遇到了麻烦。 It's run inside of WordPress, but the question shouldn't be WordPress specific. 它在WordPress内部运行,但问题不应该是WordPress特定的。 The $wpdb->get_results() is just a way to query the WordPress database without having to use a connection string. $ wpdb-> get_results()只是查询WordPress数据库的一种方式,而不必使用连接字符串。 I also use a couple of $_GET commands. 我还使用了几个$ _GET命令。

Here's what I have so far: 这是我到目前为止的内容:

$Data = $wpdb->get_results("SELECT *
    FROM database.table
    WHERE sem.MonthNum >= " .$_GET["minMonth"]. "
    AND sem.MonthNum <= " .$_GET["maxMonth"]. "
    AND sem.Year  >= " .$_GET["minYear"]. "
    AND sem.Year <= " .$_GET["maxYear"]. ");

This works, so long as the $_GET is populated. 只要填充$ _GET,此方法就起作用。 I'd like to add a kind of default value such that if $_GET is empty, a number is set, and if it's not empty, it grabs that number. 我想添加一种默认值,例如,如果$ _GET为空,则设置一个数字,如果不为空,它将获取该数字。 Something along the lines of... 类似于...

$Data = $wpdb->get_results("SELECT *
    FROM database.table
    WHERE sem.MonthNum >= " if(!$_GET){echo 1;} else {echo ".$_GET[\"minMonth\"]. "} "

But that doesn't work for me...probably some silly PHP syntax error, I'm not sure about all the echo statements and the quotes within other quotes and whatnot. 但这对我不起作用...可能是一些愚蠢的PHP语法错误,我不确定所有的echo语句以及其他引号内的引号和其他内容。

For each of your variables do this: 对于每个变量,请执行以下操作:

$minMonth = isset($_GET["minMonth"]) ? intval($_GET["minMonth"]) : 1;
... 
"WHERE sem.MonthNum >= " .minMonth. "

The intavl() call will make convert the $_GET value to an integer if it is not already, which will protect you from SQL injection security issues. intavl()调用会将$ _GET值转换为整数(如果尚未转换),这将保护您免受SQL注入安全性问题的影响。 If you need to do something similar with strings, use something like mysql_escape_string() instead. 如果您需要对字符串做类似的事情,请改用mysql_escape_string()之类的东西。

You could add a variable for each, for example: 您可以为每个变量添加一个变量,例如:

// If not set $minMonth is set to 1
$minMonth = (isset($_GET['minMonth']) ? $_GET['minMonth'] : 1);

Just do this for the other variables as well. 只需对其他变量也是如此。

You can use short hand notation like Scott and David show directly in your query: 您可以在查询中直接使用Scott和David show这样的简写形式:

$Data = $wpdb->get_results("SELECT *
FROM database.table
WHERE sem.MonthNum >= ".(!isset($_GET['minMonth'])?'1':$_GET['minMonth'])."
AND...

You really need to sanitize the variables first though, otherwise you could be SQL injected very easily. 不过,您确实确实需要先清理变量,否则可以很容易地将SQL注入。

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

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