gpt4 book ai didi

php - laravel 5 搜索多个字段

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

我在多个搜索字段中有一个 php 代码,但我不知道如何在 laravel 中使用此功能

laravel 中的 mysql 语法在简单的 php 中并不相同,所以我如何编译它。

if(isset($_GET['submit'])) {
// define the list of fields
if(isset($_GET['debit']) && !empty($_GET['debit'])) {

$_GET['valeur'] = - $_GET['debit'];
}
else
{
if(isset($_GET['credit']) && !empty($_GET['credit']))
{
$_GET['valeur'] = $_GET['credit'];
}
}
$fields = array('id_type', 'date_operation', 'date_valeur', 'numero','tiers','description','valeur');
$conditions = array();


// builds the query
$query = "SELECT * FROM ecritures WHERE id_compte ='" . $iduser . "' ";


// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_GET[$field]) && !empty($_GET[$field])) {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "$field LIKE '%" . mysqli_real_escape_string($co, $_GET[$field]) . "%'";
}
}


// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= " AND " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}}

最佳答案

Laravel 中的查询构建器使这种查询比像您的代码那样手动创建 SQL 查询要容易得多。

所以这段代码应该适合你:

$q = DB::table('ecritures ')->where('id_compte', $iduser);


// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_GET[$field]) && !empty($_GET[$field])) {
// create a new condition
$q = $q->where($field, 'LIKE', '%' . $_GET[$field] . '%');
}
}

$result = $q->get();

foreach ($result as $row) {
echo $row->column_name;
}

我还省略了 escape 函数,因为 Laravel 会为您处理。

关于php - laravel 5 搜索多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37910445/

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