0

我有一个数据库,其中有一行称为形状,并包含矩形、正方形和圆形的条目。我目前有以下代码来仅获取用户请求的形状。(目前它是矩形和圆形、正方形和圆形或只有圆形)。由于某种原因,它无法正常工作并引发数据库错误。谁能帮我?“MEMBER_FROM”是他们所在的列

$where = "";
    if($context['no_sq'] == 1 && $context['no_rec'] == 0) {
        $where .= " WHERE MEMBER_FROM != 'Square'";
    } else if($context['no_sq'] == 1 && $context['no_rec'] == 0) {
        $where .= " WHERE MEMBER_FROM != 'Rectangle'";
    } else if($context['no_sq'] == 1 && $context['no_rec'] == 1) {
        $where .= " WHERE MEMBER_FROM != 'Square' AND MEMBER_FROM != 'Rectangle'";
    }
    $request = mysql_query("SELECT ID_SHAPES FROM {$db_prefix}shapes WHERE ID_MEMBER = {$memID}{$where}", __FILE__, __LINE__);
4

2 回答 2

3

你不能说 WHERE 两次。使用和...

   $where = "";
        if($context['no_squ'] == 1 && $context['no_rec'] == 0) {
            $where .= " AND MEMBER_FROM != 'Square'";
        } else if($context['no_sq'] == 1 && $context['no_rec'] == 0) {
            $where .= " AND MEMBER_FROM != 'Rectangle'";
        } else if($context['no_sq'] == 1 && $context['no_rec'] == 1) {
            $where .= " AND MEMBER_FROM != 'Square' AND MEMBER_FROM != 'Rectangle'";
        } 

     $request = mysql_query("SELECT ID_SHAPES FROM {$db_prefix}shapes WHERE ID_MEMBER = {$memID}{$where}", __FILE__, __LINE__);

更新: 根据您的声明,您的形状是排除复选框,将这些框命名为数组然后基于循环构建查询会更有意义。否则这段代码可能很难维护......

<input type="checkbox" name="exclude[]" value="Square"> Square
<input type="checkbox" name="exclude[]" value="Rectangle"> Rectangle
<input type="checkbox" name="exclude[]" value="Circle"> Circle

然后在 PHP

foreach($_POST['exclude'] AS $exclude)
{
    $where .= " AND MEMBER_FROM != '".$exclude."'";
}

...显然转义了 $exclude var,但为简单起见,我们假设您正在转义用户输入。

于 2012-08-24T23:53:06.797 回答
0

您正在向WHERE查询中添加多个子句,这是非法的。NOT IN此外,在这种情况下,您可能更喜欢 better 的语法。请注意,我还冒昧地清理了您的逻辑结构。

$sql = "SELECT ID_SHAPES FROM {$db_prefix}shapes WHERE ID_MEMBER = {$memID}";
$disallowed = array();
if($context['no_squ']) $disallowed[] = 'Square';
if($context['no_rec']) $disallowed[] = 'Rectangle';
if(count($disallowed)) {
    $sql .= 'AND MEMBER_FROM NOT IN ("' . implode('", "', $disallowed) . '")';
}
$request = mysql_query($sql);
于 2012-08-25T00:04:20.340 回答