【问题标题】:If statement with PDO SQL query带有 PDO SQL 查询的 if 语句
【发布时间】:2021-04-20 12:59:37
【问题描述】:

有人可以帮助/建议我如何在 sql 查询中使用 if 语句吗? 我正在尝试创建一个搜索表单,其中查询只会考虑“类别”和“类型”字段(如果它们不为空)?

我已尝试以下代码,但收到错误消息:

    public static function findBySearch($data)
    {
        $location = $data['location'];
        $category = $data['category'];
        $type = $data['type'];
           
            $sql = 'SELECT * FROM posts
            WHERE location = :location';

            if ($category != '') {
            $sql .= ', category = :category';
            }

            if ($type != '') {
                $sql .= ', type = :type';
                }
       
            $db = static::getDB();
            $stmt = $db->prepare($sql);

            $stmt->bindValue(':location', $location, PDO::PARAM_STR);
           
            if ($category !='') {       
                $stmt->bindValue(':category', $category, PDO::PARAM_STR);
                }

            if ($type !='') {       
                $stmt->bindValue(':type', $type, PDO::PARAM_STR);
                } 

            return $stmt->execute();
        }

错误:

Uncaught exception: 'PDOException'

Message: 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' category = 'To Rent', type = 'House'' at line 2'

Stack trace:

#0 C:\xampp\htdocs\findingproperty\App\Models\Post.php(269): PDOStatement->execute()
#1 C:\xampp\htdocs\findingproperty\App\Controllers\Posts.php(106): App\Models\Post::findBySearch(Array)
#2 [internal function]: App\Controllers\Posts->searchAction()
#3 C:\xampp\htdocs\findingproperty\Core\Controller.php(51): call_user_func_array(Array, Array)
#4 C:\xampp\htdocs\findingproperty\Core\Router.php(121): Core\Controller->__call('search', Array)
#5 C:\xampp\htdocs\findingproperty\public\index.php(63): Core\Router->dispatch('posts/search')
#6 {main}

我们将不胜感激。

【问题讨论】:

  • 你缺少逻辑运算符。多个条件不是由逗号链接,而是由运算符 ANDOR 链接。
  • @El_Vanja 感谢您的回复。您能否建议添加逻辑运算符的正确方法是什么(我尝试在 if 语句之前添加 AND 运算符,但收到语法错误:“unexpected AND”)?
  • 停下来想一想。如果您的 PHP if 条件没有得到满足,而您最终只有一个 SQL 条件怎么办?在查询结束时,您将有一个悬空的AND。仅当您的 PHP 条件满足时才应添加它 - 即在其中。
  • @El_Vanja,非常感谢。我已经按照下面的方法更新了 if 语句,它现在运行良好。感谢您的帮助 - 非常感谢。
  • if ($category != '') { $sql .= ' AND category = :category'; } if ($type != '') { $sql .= ' AND type = :type'; }

标签: php sql pdo


【解决方案1】:

WHERE 语句中,您必须将条件与 ANDOR 连接起来,正如 cmets 中已经指出的那样。

这个呢:

public static function findBySearch($data)
    {
        $location = $data['location'];
        $category = $data['category'];
        $type = $data['type'];
           
            $sql = 'SELECT * FROM posts
            WHERE location = :location';

            if ($category != '') {
                $sql .= 'AND category = :category';
            }

            if ($type != '') {
                $sql .= 'AND type = :type';
            }
       
            $db = static::getDB();
            $stmt = $db->prepare($sql);

            $stmt->bindValue(':location', $location, PDO::PARAM_STR);
           
            if ($category !='') {       
                $stmt->bindValue(':category', $category, PDO::PARAM_STR);
                }

            if ($type !='') {       
                $stmt->bindValue(':type', $type, PDO::PARAM_STR);
                } 

            return $stmt->execute();
        }

或者你可以这样做:

public static function findBySearch($data)
    {
        $location = $data['location'];
        $category = $data['category'];
        $type = $data['type'];
           
            $sql = 'SELECT * FROM posts';
            $where = [
                [ 'column' => 'location', 'value' => $location ]
            ];

            if ($category != '') {
                $where[] = [ 'column' => 'category', 'value' => $category ];
            }

            if ($type != '') {
                $where[] = [ 'column' => 'type', 'value' => $type ];
            }
            
            if (count($where) {
                $sql .= ' WHERE '.join(' AND ', array_map(function($item) {
                    return $item['column'].' = :'.$item['value'];
                }));                
            }
       
            $db = static::getDB();
            $stmt = $db->prepare($sql);
            
            if (count($where) {
                foreach($where as $column => $value) {
                    $stmt->bindValue(':'.$column, $value, PDO::PARAM_STR);
                }
            }

            return $stmt->execute();
        }

【讨论】:

    猜你喜欢
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    相关资源
    最近更新 更多