两点注意项:

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); }

 

Refer:PDO中的占位符

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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-11
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-09
  • 2022-12-23
  • 2021-06-14
  • 2021-04-30
相关资源
相似解决方案