复选框mysql条件令人困惑:(

时间:2014-09-22 07:37:17

标签: mysql checkbox

我试图使用复选框创建搜索过滤器但是mysql OR和AND条件非常混乱。如何将其设置为显示用户检查的所有结果?这是我的代码。

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$DB_HOST = "localhost"; 
$DB_NAME = "mysite"; 
$DB_USER = "root"; 
$DB_PASS = "***"; // password edited out

$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
  die('Connection failed [' . $conn->connect_error . ']');
}




$sql="SELECT * FROM websiteusers ";
if (isset($_POST['submit'])) {
    $searchgender = isset($_POST['gender'])  ? mysqli_real_escape_string($conn,$_POST['gender']) : '';

    $searchethnicity = isset($_POST['ethnicity'])  ? mysqli_real_escape_string($conn,$_POST['ethnicity']) : '';

    $sql .= "WHERE gender = '{$searchgender}'";
    $sql .= " OR ethnicity = '{$searchethnicity}' ";
}

$query=mysqli_query($conn,$sql) or die(mysqli_error($conn));


?>

<?php
$query=mysqli_query($conn,$sql) or die(mysqli_error($conn));
?>

<form name="form" action="" method="post">
<table>
    <tr>
        <td>
            Gender:
        </td>
        <td>
            <input type="checkbox" name="gender" value="male">Male<br>
            <input type="checkbox" name="gender" value="female">Female
        </td>
    </tr>
    //more code (it says too much code lol)

2 个答案:

答案 0 :(得分:0)

你可以这样做

    $sql .= "WHERE gender = '{$searchgender}'";

   // if Gender checkbox check then add or ohter wise normal condition
   if(!empty($searchgender)){

     $sql .= " OR ";
   }
    $sql .= " ethnicity = '{$searchethnicity}' ";

答案 1 :(得分:0)

//try this
$sql="SELECT * FROM websiteusers where 1 AND ";
$searchgender = trim($_POST['gender']);
$searchethnicity = trim($_POST['searchethnicity']);
if($searchgender!='')
{
 $sql .= " gender = '".$searchgender."'";
 }
 if($searchgender!='' && $searchethnicity!='')
 $sql .=" OR ";

if($searchethnicity!='')
 $sql .= " ethnicity = '".searchethnicity."'";