dougan1465
2014-04-09 16:14
浏览 76
已采纳

PHP PDO有选择地使用bindParam

$pdo = $db_con->prepare("INSERT INTO agents (Agent_ID,Agent_Name,Agent_Branch) VALUES (?,?,?)");
$pdo->bindParam(1, $id);
$pdo->bindParam(2, $name);
$pdo->bindParam(3, $branch);
$pdo->execute();

So in this example I only need to really use bindParam on $branch because $name and $id have passed through a strict REGEX using preg_replace.

Is there a way to include these sanitised variables in the statement or any other way to shorten this code?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douhuiqi3855 2014-04-09 16:25
    已采纳

    The short way would be:

    $pdo = $db_con->prepare("INSERT INTO agents (Agent_ID,Agent_Name,Agent_Branch) VALUES (?,?,?)");
    $pdo->execute(array($id,$name,$branch));
    

    if you ever wanted to bind parameters, replace the question marks with placeholders:

    $pdo = $db_con->prepare("INSERT INTO agents (Agent_ID,Agent_Name,Agent_Branch) VALUES (:id,:name,:branch)");
    $pdo->bindParam(':id', $id);
    $pdo->bindParam(':name', $name);
    $pdo->bindParam(':branch', $branch);
    $pdo->execute();
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题