問:PDO 準備語句可以使用萬用字元嗎?
答:可以,PDO 中可以使用通配符準備好的語句,允許使用動態值進行強大的資料庫查詢。但使用方法與標準 SQL 查詢略有不同。
如何在準備語句中使用通配符:
選項 1:bindValue()
使用bindValue()方法分配包含通配符的值value.
// Set the name with wildcards
$name = "%anyname%";
// Prepare the statement
$stmt = $dbh->prepare("SELECT * FROM `gc_users` WHERE `name` LIKE :name");
// Bind the name with wildcards using bindValue()
$stmt->bindValue(':name', $name);
// Execute the statement
$stmt->execute();
選項2:bindParam()
使用bindParam()方法分配包含通配符的值,但在綁定之前修改該值。
// Set the name with wildcards
$name = "%anyname%";
// Prepare the statement
$query = $dbh->prepare("SELECT * FROM `gc_users` WHERE `name` like :name");
// Bind the name with wildcards using bindParam()
$query->bindParam(':name', $name);
// Execute the statement
$query->execute();
附加說明:
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3