PDO从数组中准备语句和bindValues

我在PDO语句中有以下代码块:

$stmt = $db->prepare("INSERT INTO first_page_data (title, first_name, surname, phone, email, add1, add2, add3, add4, add5) VALUES(?,?,?,?,?,?,?,?,?,?)");

$stmt->bindValue(1, $_POST['title'], PDO::PARAM_STR);
$stmt->bindValue(2, $_POST['first_name'], PDO::PARAM_STR);
$stmt->bindValue(3, $_POST['surname'], PDO::PARAM_STR);
$stmt->bindValue(4, $_POST['phone'], PDO::PARAM_INT);
$stmt->bindValue(5, $_POST['email'], PDO::PARAM_STR);
$stmt->bindValue(6, $_POST['add1'], PDO::PARAM_STR);
$stmt->bindValue(7, $_POST['add2'], PDO::PARAM_STR);
$stmt->bindValue(8, $_POST['add3'], PDO::PARAM_STR);
$stmt->bindValue(9, $_POST['add4'], PDO::PARAM_STR);
$stmt->bindValue(10, $_POST['add5'], PDO::PARAM_STR);
$stmt->execute();
$_SESSION['buyer_email'] = $_POST['email'];

这些参数(标题,名字等)可以使用数组和for each循环放入bindValues吗? 我可以通过只包含标题的数组来获取prepare语句,但似乎无法获取$ _POST值中的变量名称。 这将节省相当多的代码,但我不能完全达到目的!

以下是我要在绑定值循环中使用的准备语句中使用的数组:

$first = array('title','first_name','surname','phone','email','add1','add2','add3','add4','add5');

只需简单地循环$first并为每一个调用bindValue

foreach($first as $key=>$val){
    $stmt->bindValue($key+1, $_POST[$val], PDO::PARAM_STR);
}

或者你可以像这样使用它:

$stmt = $db->prepare("INSERT INTO first_page_data (title, first_name, surname, phone, email, add1, add2, add3, add4, add5) VALUES(?,?,?,?,?,?,?,?,?,?)");

$stmt->execute($array);

该数组将如下所示:

$array = array($_POST['title'],$_POST['first_name']);

或者如果您已经拥有正确的订单

  $array = $_POST;
链接地址: http://www.djcxy.com/p/93795.html

上一篇: PDO prepared statement and bindValues from an array

下一篇: connection