I'd use something like this, but there are plenty of alternatives.
if(!empty($_POST['check_num'])) {
$count = count($_POST['check_num']);
if($count <= 4){
$columns = "";
$values = "";
$i = 1;
while($i <= $count){
$columns .= "ticket".$i.", ";
$params .= "?, ";
$types .= "i";
$i++;
}
$columns = substr($columns, 0, 2);
$params = substr($columns, 0, 2);
$stmt = $mysqli->prepare("INSERT INTO [table_name] (".$columns.") VALUES (".$params.");";);
mysqli_stmt_bind_param($stmt, $types, ...$_POST['check_num']);
mysqli_stmt_execute($stmt);
}
else{
echo "Too many selections";
}
}
else{
echo "empty";
}
I haven't used anything but PDO for prepared in php in several years. Might be my bias but I'd recommend the switch, this seemed more complicated to me. You may need to update the portions using mysqli prepare and bind I haven't tested this code at all, just wrote it in the answer.
I also assumed each column was an integer type, and of course, update to use your table name in the query.
I added the substr()
functions to remove trailing ", "
from last entry of each, you could also check if $i == $count
before those assignments, and use a different assignment set without the trailing ", "
inside that if()
with the current assignments in the following else
. The $i++
would obviously be outside this if()/else
.