【问题标题】:How can I prepare a statement like the following using PHP PDO?如何使用 PHP PDO 准备如下语句?
【发布时间】:2015-04-16 08:24:41
【问题描述】:
$sql = "SELECT * FROM cc_agent";

if (isset($_POST["submit"]))    {
    $srch = htmlspecialchars($_POST["search_user"]);
    $sql .= " WHERE ";

    if (empty($srch))   {
        $sql = "";
    } else
    {
        $sql .= "login LIKE '%{$srch}%' OR lastname LIKE '%{$srch}%' OR email LIKE '%{$srch}%' OR firstname LIKE '%{$srch}%'";
    }
}

我想用 PDO 查询更改我的所有程序查询。我有上面的代码,它搜索许多变量并使用通配符。任何帮助将不胜感激。

【问题讨论】:

  • 你在哪里准备的声明?
  • 谢谢大家。解决了。​​

标签: php mysql pdo


【解决方案1】:

如何创建 PDO 连接:http://php.net/manual/en/pdo.connections.php

您的示例查询

$srch = 'something';
$srch2 = 'otherthing';

$sth = $dbh->prepare('SELECT * FROM cc_agent WHERE login LIKE :srch OR lastname LIKE :srch2');
$sth->bindParam(':srch', '%'.$srch.'%');
$sth->bindParam(':srch2', '%'.$srch2.'%');
$sth->execute();

更多关于bindParam的有用资源:http://php.net/manual/en/pdostatement.bindparam.php

【讨论】:

    【解决方案2】:
    if (isset($_POST["submit"]))    {
        $srch = htmlspecialchars($_POST["search_user"]);
        $sql .= " WHERE ";
    
        if (empty($srch))   {
            $sql = "";
        } else
        {
            $sql .= "login LIKE ? OR lastname LIKE ? OR email LIKE ? OR firstname LIKE ?";
        }
    }
    $stmt = $dbh->prepare($sql);
    $stmt->execute(array($srch, $srch, $srch, $srch));
    
    
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC))   {
        extract($row);
        echo $variable1, $variable2;
    }
    

    感谢各位的帮助。尝试了上面的代码,它工作得很好。干杯!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-25
      • 2020-04-14
      • 2010-11-30
      • 2014-04-19
      • 2013-04-21
      • 1970-01-01
      • 2010-11-18
      相关资源
      最近更新 更多