gpt4 book ai didi

php - 如何使用 PDO 准备好的语句使搜索表单适用于多个字段

转载 作者:行者123 更新时间:2023-11-29 21:45:45 25 4
gpt4 key购买 nike

大家好, 我正在尝试使搜索表单适用于多个字段。用户可以自由填写他想要的任何字段,并将其他字段留空。搜索框看起来像这样。

底部带有结果表的搜索框图像: enter image description here

我知道如何在没有 PDO 的情况下使用旧的 mysql 代码使其工作。用于搜索的 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'];
}

但是我很难弄清楚如何执行多个字段并使用准备好的语句。即使是正确方向的提示也会非常有帮助。

提前谢谢大家。

最佳答案

您可以像以前一样这样做:

$fields = array('first_name', 'last_name', 'email', 'job', 'country', 'city');
$inputParameters = array();

foreach ($fields as $field) {
// don't forget to validate the fields values from $_POST
if (!empty($_POST[$field])) {
$inputParameters[$field] = '%' . $_POST[$field] . '%';
}
}

$where = implode(' OR ', array_map(function($item) {
return "`$item` LIKE :$item";
}, array_keys($inputParameters)));

$search = $db->prepare("SELECT `id`, `name` FROM `users` WHERE $where");
$search->execute($inputParameters);

foreach ($search->fetchAll(PDO::FETCH_ASSOC) as $row) {
var_dump($row);
}

关于php - 如何使用 PDO 准备好的语句使搜索表单适用于多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34133968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com