如何准备一个带有大量if语句的预处理语句?

3

我有大约25个可选字段用于我的SQL查询。我的做法是,使用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的查询,但是在执行查询之前,如何按正确的顺序分配值?

非常感谢您的任何帮助。


2
听起来你的数据库还没有规范化。 - e4c5
@e4c5 很抱歉,但是为什么呢?数据库完全正常(当然不属于我:-)),我只是想不出使用预处理语句将可选参数包含到最终查询中的最简单方法。 - Lunatic Fnatic
一张有25列的表听起来有点奇怪。 - e4c5
@e4c5 哦,你说得完全正确,但是必须这样做。它大约有25M个记录,但有趣的是它非常高效。 - Lunatic Fnatic
3
将它们放入一个数组中,然后在你的 pg_execute 中使用它,我认为你不必担心顺序问题。 - A. Mesut Konuklar
@A.MesutKonuklar,您能否解释一下如何在不打乱顺序的情况下插入via数组? - Lunatic Fnatic
1个回答

3

尝试这种方法

// 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);

You would have the following output

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 )


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接