大家好, 我正在尝试使用多个字段进行搜索表单。用户可以自由填充他希望的任何字段并将其他字段留空。搜索框看起来像这样。
我知道如何在没有旧的mysql代码的PDO的情况下使其工作。 用于搜索的PHP代码是:
<?php
if(isset($_POST['submit'])){
// define the list of fields
$fields = array('first_name', 'last_name', 'email', 'job', 'country', 'city');
$conditions = array();
// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && $_POST[$field] != '') {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "`$field` LIKE '%" . mysql_real_escape_string($_POST[$field]) . "%'";
}
}
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("php_test", $con) or die("ERROR");
// builds the query
$query = "SELECT * FROM people ";
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= "WHERE " . implode (' OR ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
// echo $query;
$result = mysql_query($query);
}
?>
(注意:我没有包含任何验证,但我会这样做)
它的工作正常,但我想用PDO做同样的事情。
我知道如果我执行类似下面的代码,它将在PDO中起作用: -
$q = $_POST['q'];
$search = $db->prepare("SELECT `id`, `name` FROM `users` WHERE `name` LIKE ?");
$search->execute(array("%$q%"));
foreach($search as $s) {
echo $s['name'];
}
但是我很难弄清楚如何在多个字段中使用并使用预处理语句。即使是正确方向的暗示也会非常有帮助。
先谢谢大家。
答案 0 :(得分:0)
你可以像以前那样做:
../main.c:42:26: error: ‘dateTime’ undeclared (first use in this function)
DS3231_get_dateTime( &dateTime );
答案 1 :(得分:0)
你可以这样做
$q = $_POST['q'];
$query = "SELECT `id`, `name` FROM `users` WHERE ";
// loop over submitted input keywords
foreach($keywords as $keyword){
$query .= $keyword . " LIKE ? ";
}
$sql=$db->prepare($query);
// loop over submitted input values array
foreach($values as $k => $value){
$sql->bindParam($k+1, '%'.$value.'%');
}
$sql->execute ();