1

trying to bind parameters of an sql statement in php using a loop, I get all the parameters equal to the last one. here's my code :

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

Using this I get a new line in the "Formations" Table with these values phpMyAdmin the repeated "1" is the repeated value of the last binded variable which is : $idTypeFormation

NB I use php7.2 with Apache. Thank you.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • 1
    You're binding the parameter `$value`, not the individual values. Try [`bindValue`](https://secure.php.net/manual/en/pdostatement.bindvalue.php) instead. – aynber Dec 07 '18 at 14:49

0 Answers0