我有一个数据库,其中有一行称为形状,包含带有矩形,正方形和圆形的条目。我目前有以下代码,只获得用户请求的形状。 (目前它是矩形和圆形,正方形和圆形或仅圆形)。由于某种原因,它不起作用并抛出数据库错误。谁能帮我? “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__);
答案 0 :(得分:3)
你不能说WHERE两次。使用AND ...
$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,但为了简单起见,我们假设您正在逃避用户输入。
答案 1 :(得分:0)
您在查询中添加了多个WHERE
子句,这是非法的。此外,在这种情况下,您可能更喜欢NOT IN
的语法。请注意,我也冒昧地清理了你的逻辑结构。
$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);