我的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 )
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。