首页 > 解决方案 > 为什么我在 php 语句中得到错误的绑定值?

问题描述

尝试使用循环在 php 中绑定 sql 语句的参数,我得到的所有参数都等于最后一个参数。这是我的代码:

$nomTypeFormation   = "Types";
$nomFormation       = "Nomss";
$prixHTFormation    = 00;
$taxeFormation      = 00;
$dureeFormation     = 10;
$idTypeFormation    = 1;
$data=[
    $nomFormation,
    $dureeFormation,
    $prixHTFormation,
    $taxeFormation,
    $idTypeFormation
];
$requestConnexion = "mysql:host=localhost;dbname=EcoleFormationsDB";

try {
    $db = new PDO($requestConnexion, "root", "root");
} catch (\Exception $e) {
    echo "Failed connect to DB : ".$e->getMessage();
}

$query = "INSERT INTO Formations VALUES (NULL, ?, ?, ?, ?, ?)";
$st = $db->prepare($query);
foreach ($data as $key => $value) {
    $st->bindParam($key +1, $value);
}
// $st->bindParam(1, $nomTypeFormation);
// $st->bindParam(2, $dureeFormation);
// $st->bindParam(3, $prixHTFormation);
// $st->bindParam(4, $taxeFormation);
// $st->bindParam(5, $idTypeFormation);
$st->execute();

使用它,我在“Formations”表中得到一个新行,其中包含这些值 phpMyAdmin ,重复的“1”是最后一个绑定变量的重复值,即:$idTypeFormation

注意我使用 php7.2 和 Apache。谢谢你。

标签: phparrayspdoforeach

解决方案


推荐阅读