PDO prepared statement and bindValues from an array

I have the following block of code in a PDO statement:

$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'];

Can these parameters (title, first_name, etc) be put into the bindValues using an array and a for each loop? I can get the prepare statement working by just having an array containing the titles but cant seem to get the variable names inside the $_POST values. It would save quite a few lines of code, but I cant quite get there!

The following is the array im using in the prepared statement that I want to use in the bind value loop:

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

Or you can use it like this:

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

$stmt->execute($array);

The array would be like:

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

or if you have the correct order already just

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

上一篇: PGSQL驱动程序支持准备语句?

下一篇: PDO从数组中准备语句和bindValues