我有一个提交以下内容的表单:
状态 城市 类别
我的查询需要执行以下操作:
如果只选择状态 - 显示状态结果
如果选择了州和猫 - 显示州和猫的结果
如果选择州和城市 - 显示州和城市结果
如果选择了州、城市和猫 - 显示州、城市、猫结果
问题是当他们提交城市时,需要检查 3 个不同的字段是否匹配
这是我的查询,它不起作用,我已经尝试了 100 种不同的变体。很抱歉成为这样的新手。提前感谢您的帮助。
$sql = "SELECT * FROM items WHERE state=$st AND city1='$_GET[city] OR
city2='$_GET[city]' OR city3='$_GET[city]' OR cat='$_GET[cat]'
AND active='1'
ORDER BY item_id DESC LIMIT $limitvalue, $limit ";
$result=mysql_query($sql);
while ($prow=mysql_fetch_array($result))
{
最佳答案
我个人不太擅长做 MySQL 查询字符串,我通常使用类似于此的 sql 编译器类(请记住,这只是一个快速的)。它允许绑定(bind),这是你需要的,尤其是像你这样的 $_GET
值:
class ItemQueue
{
protected $sql;
protected $wherevals;
public $bind;
public $compiled;
public function select($values = false)
{
$this->sql[] = "select";
if($values == false)
$this->sql[] = "*";
else
$this->sql[] = $values;
return $this;
}
public function from($table = false)
{
if($table ==false)
return $this;
$this->sql[] = "from `$table`";
return $this;
}
public function where($values = array(),$op = 'and')
{
if(!empty($values)) {
$this->sql[] = 'where';
foreach($values as $key => $values) {
$this->wherevals[] = $key.' = :'.$key;
// Bind values for injection protection
$this->bind[":$key"] = $values;
}
$this->sql[] = implode(" $op ",$this->wherevals);
// This part is a bit jenky but you get the idea
$this->sql[] = "and active = '1'";
}
return $this;
}
public function customsql($values = false)
{
if($values != false) {
$this->sql[] = $values;
}
return $this;
}
public function Fetch()
{
// Implode entire sql statement
$this->compiled = implode(" ", $this->sql);
return $this;
}
}
// Post/Get values
$_POST['cat'] = 'cattest';
$_POST['city'] = 'Reno';
$_POST['state'] = 'Nevada';
// Arbitrary limits
$limit = 1;
$limitvalue = 1;
// Create instance
$tester = new ItemQueue();
// Just set some array filtering/validating
if(isset($_POST['cat']) && !empty($_POST['cat']))
$array['cat'] = $_POST['cat'];
if(isset($_POST['city']) && !empty($_POST['city']))
$array['city'] = $_POST['city'];
if(isset($_POST['state']) && !empty($_POST['state']))
$array['state'] = $_POST['state'];
// Make the query
$query = $tester->select()->from("items")->where($array,"or")->customsql("ORDER BY item_id DESC LIMIT $limitvalue, $limit");
// Here is the sql statement
echo $query->Fetch()->compiled;
// Bind array
print_r($query->bind);
给你:
select * from `items` where cat = :cat or city = :city or state = :state and active = '1' ORDER BY item_id DESC LIMIT 1, 1
Array
(
[:cat] => cattest
[:city] => Reno
[:state] => Nevada
)
请注意,这需要您使用正确的连接(PDO 在这种情况下效果最好)。
关于php - 如何编写mysql查询来检查表单提交可以匹配1 0f 5字段的多个变量选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28446088/