需要在php脚本中编写一个mySQL查询,它将随着每个提交会话中用户输入的更改而自动更改
我有一个mySQL数据库,如下所示: 我有一个带有提交按钮的复选框表单,如下所示 a[]b[]c[]提交] 用户可以选择这些选项中的任何一个,然后按Submit 基于此, 我需要在我的php脚本中编写一个mysql查询,它将随着每个提交会话中用户输入的变化而变化。 eg1 用户选择 a[x]b[]c[x][Submit] 根据我的php脚本需要在php脚本中编写一个mySQL查询,它将随着每个提交会话中用户输入的更改而自动更改,php,mysql,sql,forms,checkbox,Php,Mysql,Sql,Forms,Checkbox,我有一个mySQL数据库,如下所示: 我有一个带有提交按钮的复选框表单,如下所示 a[]b[]c[]提交] 用户可以选择这些选项中的任何一个,然后按Submit 基于此, 我需要在我的php脚本中编写一个mysql查询,它将随着每个提交会话中用户输入的变化而变化。 eg1 用户选择 a[x]b[]c[x][Submit] 根据我的php脚本 $a=1 $b=0 $c=1 $a=1 $b=1 $c=0 现在,我的查询应该会自动读取上述值,并变成: select name from table
$a=1
$b=0
$c=1
$a=1
$b=1
$c=0
现在,我的查询应该会自动读取上述值,并变成:
select name from table1 where a=$a AND c=$c;
select name from table1 where a=$a AND b=$b;
这应该会给我结果:
x1
x2
x2
x4
eg2
用户选择
a[x]b[x]c[][Submit]
根据我的php脚本
$a=1
$b=0
$c=1
$a=1
$b=1
$c=0
现在,我的查询应该会自动读取上述值,并变成:
select name from table1 where a=$a AND c=$c;
select name from table1 where a=$a AND b=$b;
这应该会给我结果:
x1
x2
x2
x4
基本上,无论哪个复选框保持未选中状态,我们都必须在查询中忽略它。我想您正在尝试查询复选框所代表的特定列。如果将这些值压缩到一个数组中,则可以对它们进行迭代,并删除任何具有零值的值,如下所示:
<?php
$a=1;
$b=0;
$c=1;
$array = compact("a", "b", "c"); // convert vars into an array
$wherePart = '';
foreach ( $array AS $key => $value ) {
if ( $value ) {
$wherePart .= "$key = $" . $key . ' AND '; // build var with items containing values
}
}
$query = "select name from table1 where " . rtrim($wherePart, ' AND ');
// select name from table1 where a = $a AND c = $c
以下是一个工作示例
<?
if (isset ($_POST['submit']) ):
$Where = "";
extract($_POST);
if (!empty($a) || !empty($b) || !empty ($c))
$Where = "where ";
if (! empty($a))
$Where .= "a = $a ";
if (! empty($a) && ! empty($b))
$Where .= 'and ';
if (! empty($b))
$Where .= "b = $b ";
if (! empty($b) && ! empty($c))
$Where .= 'and ';
if (! empty($c))
$Where .= "c = $c";
echo $Where;
endif;
?>
试试这个
select name from table1 where a like '%$a%' AND b like '%$b%' AND c like '%$c%'
我试过这个,它成功了。与艾哈迈德的建议非常相似
if($a == 1)
$str1 = "a=1 and ";
else $str1 = "";
if($b == 1)
$str2 = "b=1 and ";
else $str2 = "";
if($c == 1)
$str3 = "c=1 and ";
else $str3 = "";
$sqlstd="select name from table1 where ";
$sqltmp=$sqlstd.$str1.$str2.$str3;
$sql=chop($sqltmp,"and ");
echo $sql;
然后进一步使用$sql输出查询结果。
这是更硬的编码,但我想在这种情况下可以,因为我知道我的表只有0或1个值,复选框勾选将导致1或0。我实际上尝试了许多不同的and-or组合。将表中的0更改为-1,以便我的用户输入值为0或1,我认为可以使用该值进行查询,但我似乎什么都找不到。我知道这是我必须要做的,但是我不知道用什么语法来做。