【问题标题】:PDO prepared statement and bindValues from an array数组中的 PDO 准备好的语句和 bindValues
【发布时间】:2014-03-27 18:51:39
【问题描述】:

我在 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 循环将这些参数(title、first_name 等)放入bindValues 吗?我可以通过一个包含标题的数组来使准备语句工作,但似乎无法在 $_POST 值中获取变量名。它会节省不少代码,但我无法到达那里!

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

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

【问题讨论】:

    标签: php pdo


    【解决方案1】:

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

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

    【讨论】:

    • 好吧,结果证明我只是将 $first 代替准备好的语句中的列表的想法行不通!它返回一个数组到字符串的转换——有什么想法吗?另外,我是否可以假设因为它不是关联数组,所以您提到的 $key 只是索引(从 0 开始,因此是 +1),而 $val 是数组中的字符串?
    • @Giovanni:“在准备好的语句中用 $first 代替列表”是什么意思?
    • @Giovanni: $key 我们是数组的索引(它从 0 开始)。 bindValue() 从 1 开始,这就是我使用 +1 的原因。 $value 是数组中的字符串,所以$_POST[$val] 从 POST 数组中获取值。
    • 我有 "INSERT INTO first_page_data (长参数列表),但我想用数组的名称替换列表包含列表。只需用 $first 替换列表就会返回错误....
    • @Giovanni:$sql = 'INSERT INTO first_page_data (' . implode(',',$first) . ') VALUES (' . implode(',', array_fill(0, count($first), '?')) . ')';。您想使用implode 将数组转换为字符串。
    【解决方案2】:

    或者你可以这样使用它:

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

    【讨论】:

      猜你喜欢
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 2014-07-20
      • 2013-12-28
      • 1970-01-01
      • 1970-01-01
      • 2010-11-30
      相关资源
      最近更新 更多