我在数据库中有一个包含列名的表:
Name
Department
organization
location
year
email
我的表单有3个名称属性值:department
,year
,organization
。
当用户填写任何这些属性时,我希望将其发布到我的PHP脚本,然后该脚本将仅根据填充的属性查询结果。
例如:
如何修改我的下面的查询脚本,以便获得所需的结果?
// Conneced to server and select database.
$sql="SELECT * FROM $tbl_name WHERE dept =$_post['dept'] and year =$_post['year'] and company =$_post['commpany'];
$result = mysql_query($sql);
while($rows=mysql_fetch_array($result)) {
?>
答案 0 :(得分:0)
你应该使用动态的地方
$where = "WHERE 1 ";
if(isset($_POST['dept']) && $_POST['dept']!="")
{
$dept = mysql_real_escape_string($_POST['dept']);
$where .= " AND dept='$dept' ";
}
if(isset($_POST['year']) && $_POST['year']!="")
{
$year = mysql_real_escape_string($_POST['year']);
$where .= " AND year='$year' ";
}
if(isset($_POST['commpany']) && $_POST['commpany']!="")
{
$commpany = mysql_real_escape_string($_POST['commpany']);
$where .= " AND commpany='$commpany' ";
}
$sql="SELECT * FROM `$tbl_name` ".$where;
注意: mysql_*
已被弃用[{1}}或mysqli_*