zoukankan      html  css  js  c++  java
  • [PHP]PDO占位符预处理在 IN 和 LIKE 中用法

    两点注意项:

    1. 占位符 (?) 必须被用在整个值的位置,不需要引号等其它字符。

    2. 参数按数组元素顺序依次传递给占位符。

    <?php
    /**
     * PDO基于占位符的查询预处理
     *
     * @license Apache
     * @author farwish <farwish(a)foxmail.com>
     */
    $pdo = new PDO('mysql:host=127.0.0.1;dbname=xxx;port=3306', 'root', 'xxx');
    // LIKE 查询预处理 $param1 = "上海"; $sql1 = "select * from sys_city where city_name like ?"; $stmt1 = $pdo->prepare($sql1); if ($stmt1->execute([ "%$param1%", ]) ) { $res1 = $stmt1->fetchAll(PDO::FETCH_ASSOC); print_r($res1); }
    // IN 查询预处理 $param2 = [1,2,3]; $prepare = rtrim( str_pad('?', 2 * count($param2), ',?') , ','); $sql2 = "select * from sys_city where city_id in($prepare)"; $stmt2 = $pdo->prepare($sql2); if ($stmt2->execute($param2)) { $res2 = $stmt2->fetchAll(PDO::FETCH_ASSOC); print_r($res2); }
    // 普通条件查询预处理 $param3 = "上海市"; $sql3 = "select * from sys_city where city_name = ?"; $stmt3 = $pdo->prepare($sql3); if ($stmt3->execute([ $param3, ])) { $res3 = $stmt3->fetchAll(PDO::FETCH_ASSOC); print_r($res3); }

    Source: https://github.com/farwish/php-lab/blob/master/function_reference/Database_Extensions/pdo_prepare.php

    Link: http://www.cnblogs.com/farwish/p/8059696.html

  • 相关阅读:
    BD String
    1114
    1083
    1084
    1108
    1087
    1145
    1217
    1164
    反射
  • 原文地址:https://www.cnblogs.com/farwish/p/8059696.html
Copyright © 2011-2022 走看看