I have this code for inserting prepared values into MySQL with PDO, but am looking for a way to tidy it up with a loop, to avoid repetition:
// PDO connect
$pdo = new PDO($sqldsn, $sqluser, $sqlpass, $sqlopt);
// Prepare query
$stm = $pdo->prepare("$query");
// Cycle through additional values
foreach(func_get_args() as $arg) {
$sqlarray[] = $arg;
}
// Execute query with values
$count = count($sqlarray);
if ($count == "2") { $stm->execute([$sqlarray[1]]); }
if ($count == "3") { $stm->execute([$sqlarray[1], $sqlarray[2]]); }
if ($count == "4") { $stm->execute([$sqlarray[1], $sqlarray[2], $sqlarray[3] ]); }
if ($count == "5") { $stm->execute([$sqlarray[1], $sqlarray[2], $sqlarray[3], $sqlarray[4] ]); }
if ($count == "6") { $stm->execute([$sqlarray[1], $sqlarray[2], $sqlarray[3], $sqlarray[4], $sqlarray[5] ]); }
if ($count == "7") { $stm->execute([$sqlarray[1], $sqlarray[2], $sqlarray[3], $sqlarray[4], $sqlarray[5], $sqlarray[6] ]); }
// Fetch all
$result = $stm->fetchAll();
// Return result
return $result;
I've tried looping like this, but I don't get any results (other than the number of array entries):
for ($i = 1; $i<=$count; $i++){
echo $i;
$stm->execute([$sqlarray[$i]]);
}
I also tried to construct the sections using eval(), but understand that this isn't a safe idea for security reasons.
I just need it to cycle through as per my code, but without having to specify each number of possible prepared ? values. Can anyone help? Sorry for the newb question, but I'm currently learning PHP.