我在php代码中编写小的mysql select查询,在select查询中它有三个不同的where条件,如
SELECT * FROM table1 WHERE pid = $pid AND qid = $qid AND text="$text" ;
动态地它将改变变量,有时候变量中的一个变为null,那时我的条件看起来像
SELECT * FROM table1 WHERE pid = $pid AND text="$text" ;
同样的事情可以是文本和pid,我怎么能这样做,有没有任何解决方案,或者我必须在php中切换if / switch条件..
答案 0 :(得分:0)
您可以使用if
来创建查询并执行PDO预处理语句(http://php.net/manual/en/pdo.prepare.php)。
<?php
$query = "SELECT * FROM table1 WHERE 1 = 1";
$params = array();
if(null !== $pid) {
$query .= ' AND pid = :pid';
$params[':pid'] = $pid;
}
if(null !== $qid ) {
$query .= ' AND qid = :qid';
$params[':qid'] = $qid;
}
if(null !== $text) {
$query .= ' AND text = :text';
$params[':text'] = $text;
}
$sth = $dbh->prepare($query);
$sth->execute($params);
$result = $sth->fetchAll();
答案 1 :(得分:0)
这是另一个mysql变体:
SELECT *
FROM tbl
WHERE
IF($pid > 0, pid = $pid, 1 = 1)
AND IF($qid > 0, qid = $qid, 1 = 1)
AND IF($text > '', `text` = $text, 1 = 1)
;
但这里硬编码的价值观。而且你不能选择pid或qid正好等于0或text等于''(空字符串)的行。
你可以接收将选择表格中所有行的查询,我想它会非常糟糕......
腓:
<?php
$dbh = new PDO('mysql:dbname=test;host=127.0.0.1', 'root');
$pid = 1;
$qid = 2;
$text = '3';
$sql = 'SELECT * FROM tbl WHERE 1 = 1';
$params = [];
if (isset($pid)) {
$sql .= ' AND pid = :pid';
$params[':pid'] = $pid;
}
if (isset($qid)) {
$sql .= ' AND qid = :qid';
$params[':qid'] = $qid;
}
if (isset($text)) {
$sql .= ' AND `text` = :text';
$params[':text'] = $text;
}
$sth = $dbh->prepare($sql);
$sth->execute($params);
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
var_export($result);
答案 2 :(得分:-1)
您可以将其包含在SQL中,如下所示:
treeListView1.Expand(br.Model);
MySql-Server将看到SELECT *
FROM table1
WHERE ("$pid" = "" OR pid = "$pid")
AND ("$qid" = "" OR qid = "$qid")
AND ("$text" = "" OR text="$text") ;
并在执行之前优化查询,方法是删除此部分。