php-如何使用很多if语句准备一条准备好的语句?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php-如何使用很多if语句准备一条准备好的语句?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2303字,纯文字阅读大概需要4分钟。
内容图文
![php-如何使用很多if语句准备一条准备好的语句?](/upload/InfoBanner/zyjiaocheng/665/e92b4f7eb3ea4936991a66dcf7e20265.jpg)
我的SQL查询有大约25个可选字段.我正在做的是,使用ajax(用于分页)将数据发布到另一个php文件中,以准备和执行查询.
样本(index.php)
// Get optional value
if (isset($_POST['il']) && !empty($_POST['il'])) $il = $_POST['il'];
// JS
change_page('0');
});
function change_page(page_id) {
var dataString = page_id;
// Define optional value
<?php if (isset($_POST['il'])&& !empty($_POST['il'])):?>
var il = '<?php echo $il;?>';
<?php endif; ?>
// Send optional value
$.ajax({
type: "POST",
url: "includes/post.php",
data: {
<?php if (isset($_POST['il'])&& !empty($_POST['il'])):?>'il': il,<?php endif; ?> },
...
Post.php(处理操作的位置)
...
// Main Query (default)
$bas_query = "SELECT id, a, b, c, d, e FROM test.db WHERE a=$1 AND b=$2";
// If user has an input for 'il', add it to query.
if (isset($_POST['il']) && !empty($_POST['il'])) {
$il = $_POST['il'];
$bas_query. = ' AND city='.$il;
}
// How it's executed after statements (without ifs included)
$exec = pg_prepare($postgre,'sql2', 'SELECT id, a, b, c, d, e FROM test.db WHERE a=$1 AND b=$2 OFFSET $3 LIMIT $4');
$exec = pg_execute($postgre,'sql2', array($1,$2,$3,$4));
我的问题是,如何准备带有许多if语句的准备好的语句?我可以串联并准备pg_prepare的查询,但是在以正确的顺序执行查询之前如何分配值呢?
在此先感谢您的帮助.
解决方法:
试试这个方法
// Change your query to below
$bas_query = "SELECT id, a, b, c, d, e FROM test.db WHERE";
// Initiate your array and counter for prepared statement
$data = array();
$counter = 1;
// I assume you assigned a and b value same as below
...
// Add data to the array for each case
if (isset($_POST['il']) && !empty($_POST['il']))
{
$il = $_POST['il'];
$bas_query.= ' AND city=$' . $counter;
$counter++;
$data[] = $il;
}
... /* other if statements */
// To prepare and execute the statement; (after all the if statements)
/* A) concatenate OFFSET and LIMIT end of your final query
B) insert the OFFSET and LIMIT value to the array */
$bas_query.= ' OFFSET $' . $counter . ' LIMIT $' . ($counter + 1);
$data[] = $your_offset_val;
$data[] = $your_limit_val;
$exec = pg_prepare($postgre, 'sql2', $bas_query);
$exec = pg_execute($postgre, 'sql2', $data);
您将获得以下输出
SELECT id, a, b, c, d, e FROM test.db WHERE a=$1 AND b=$2 AND city=$3 OFFSET $4 LIMIT $5
Array ( [0] => a_value [1] => b_value [2] => city_value [3] => offset_value [4] => limit_value )
内容总结
以上是互联网集市为您收集整理的php-如何使用很多if语句准备一条准备好的语句?全部内容,希望文章能够帮你解决php-如何使用很多if语句准备一条准备好的语句?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。