php和mysql过滤器

ajsxfq5m  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(372)

我正在尝试用mysql和php创建一个过滤器。在我的数据库中,我有许多字段,如:姓名,电话号码,电子邮件。。。即使我做了

if(!empty($_POST['name'])){ 
$name=$_POST['name']
}
if(!empty($_POST['phoneNumber'])){ 
   $phoneNumber= $_POST['phoneNumber']
    }
if(!empty($_POST['email'])){ 
    $email=$_POST['email']
    }

如果有人只输入name字段,如何不在查询中包含其他字段?

$query=query("SELECT * FROM clients WHERE clientName=$clientName && phoneNumber=$phoneNumber && email=$email)
gzszwxb4

gzszwxb41#

我所做的就是在一个json对象中发送所有的搜索词。所以在javascript中,我收集所有的搜索输入,并有一个对象,其中每个键对应于输入的名称,每个值对应于val

var searchObj = {};
$(".searchInput").each(function() {
     searchObj[$(this).attr('name')] = $(this).val();
});
var searchJSON = JSON.stringify(searchObj);
//later send searchJSON to php

//in php
$seachObj = json_decode($_POST["searchJSON"], true);
$sql = "SELECT * in CLIENTS WHERE ";
foreach($searchObj as $key => $val) {
    $sql .= "$key = '$val' AND ";
}
$sql .= "1";

现在这是完全不安全的!!!只是为了清楚起见。最好使用pdo或mysqli,使用准备好的语句。这样地:

$seachObj = json_decode($_POST["searchJSON"], true);
$sql = "SELECT * in CLIENTS WHERE ";
$vals = [];
foreach($searchObj as $key => $val) {
    $vals[] = $val;
    $sql .= "$key = ? AND ";
}
$sql .= "1";
//learn more about PDO to get this part
$stmt = $pdo->prepare($sql);
$stmt->execute($vars);
wtzytmuj

wtzytmuj2#

你可以试试下面给出的方法

if(!empty($_POST['name'])){ 
$name=$_POST['name'];
$query="SELECT * FROM clients WHERE clientName='$name'";
}
if(!empty($_POST['phoneNumber'])){ 
   $phoneNumber= $_POST['phoneNumber'];
   $query.= " AND phoneNumber='$phoneNumber'";
    }
if(!empty($_POST['email'])){ 
    $email=$_POST['email'];
    $query.= " AND email='$email'";
    }

note:use prepared 查询,因为这会受到sql注入攻击。这只是演示。

oalqel3c

oalqel3c3#

我想这样就行了。

$condition = "";

if(!empty($_POST['name'])){ 
$name=$_POST['name'];
$condition .= " AND clientName LIKE ".$name;
}
if(!empty($_POST['phoneNumber'])){ 
   $phoneNumber= $_POST['phoneNumber'];
    $condition .= " AND phoneNumber ='".$phoneNumber."'";
}
if(!empty($_POST['email'])){ 
    $email=$_POST['email'];
    $condition .= " AND email='".$email."'";
}

if(!empty($condition)){
   $query="SELECT * FROM clients WHERE ".ltrim($condition," AND");
}else{
   $query="SELECT * FROM clients";
}

相关问题