我有MYSQLI查询预处理语句的问题,我想根据post值过滤掉代码。
这是我的代码
$arrfilter = array();
if(!empty($_POST['website'])){
$website = $conn->real_escape_string($_POST['website']);
array_push($arrfilter,"website='$website'");
}
if(!empty($_POST['gamename'])){
$gamename = $conn->real_escape_string($_POST['gamename']);
array_push($arrfilter,"gamename='$gamename'");
}
if(!empty($_POST['action'])){
$action = $conn->real_escape_string($_POST['action']);
array_push($arrfilter,"action='$action'");
}
if(count($arrfilter) > 0){
$filter = implode(' and ',$arrfilter);
}
$fdate= "%$date%";
$sql = "SELECT url,referrer,ip,user_agent,action,date FROM cpa_track WHERE date LIKE ? and ? ORDER BY date DESC";
$process = $conn->prepare($sql);
$process->bind_param('ss',$fdate,$filter);
$process->execute() or die("Error: ".$conn->e
rror);
$process->store_result();
我的成就是使用$ filter作为Mysqli预处理语句的动态过滤器。我收到这个怎么办?
致命错误:在非对象
上调用成员函数bind_param()
答案 0 :(得分:2)
我使用this comment手册页上bind_param()末尾的代码将其放在一起。我使用PDO,而不是mysqli,所以我还没有真正测试过这个。虽然逻辑似乎是合理的。这个概念是您逐步构建将发送到bind_params()
的参数,然后使用reflection来应用构造的值。仅供参考,由于能够使用命名参数并多次调用bindValue()
,我发现PDO的复杂程度要低得多。
$conditions = "";
$types = "s";
$values = array($fdate);
if(!empty($_POST['website'])){
$conditions .= " AND website = ?";
$types .= "s";
$values[] = $conn->real_escape_string($_POST['website']);
}
if(!empty($_POST['gamename'])){
$conditions .= " AND gamename = ?";
$types .= "s";
$values[] = $conn->real_escape_string($_POST['gamename']);
}
if(!empty($_POST['action'])){
$conditions .= " AND action = ?";
$types .= "s";
$values[] = $conn->real_escape_string($_POST['action']);
}
$bindArray = array($types);
foreach($values as $value)
{
$bindArray[] = $value;
}
$fdate= "%$date%";
$sql = "SELECT url,referrer,ip,user_agent,action,date FROM cpa_track WHERE date LIKE ? $conditions ORDER BY date DESC";
$process = $conn->prepare($sql);
$refClass = new ReflectionClass('mysqli_stmt');
$refMethod = $refClass->getMethod("bind_param");
$refMethod->invokeArgs($process,$bindArray);
$process->execute() or die("Error: ".$conn->error);
$process->store_result();