[PHP]PDO佔位符預處理在 IN 和 LIKE 中用法

 

兩點注意項:php

1. 佔位符 (?) 必須被用在整個值的位置,不須要引號等其它字符。html

2. 參數按數組元素順序依次傳遞給佔位符。mysql

 

<?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.phpgit

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

相關文章
相關標籤/搜索