-1

I have a table that contains columns q1,q2,q3,q4,q5,.. as you can see the columns names consists of letter q and numbers i,i+1,i+2,i+3,... inside a foreach loop, I want to loop through an array and add each array element to a single column. e.g. arr = [A,B,C,D] A goes to q1, B goes to q2,.. Here is my attempt:

$selected_ans = $_POST['options'];
$answersArr = implode(' ', $selected_ans);
foreach ($answersArr as $ans) {
    // column name consisting of letter q and a numeric value
    $int = "q"+1;
    $sql = "INSERT INTO MyGuests ($int)VALUES ($ans) WHERE username = $VALID_USER";
    $conn->query($sql);
    // increment the numeric value
    $int++;
}

This does not work so how can this be correctly implemented? thanks

jimiss
  • 119
  • 1
  • 1
  • 9

1 Answers1

-1

I think this is more like what you're looking for. It's a bit sloppy, but it'll get the job done and is a good starting point for you to refactor and improve upon.

$selected_ans = $_POST['options'];
// Make sure to sanitize the raw input
foreach ($selected_ans as $k => $v) {
    $selected_ans[$k] = '"' . mysqli_real_escape_string($v) . '"';
}
// Dynamically create a list of column names
$columns = [];
for ($i = 1; $i <= count($selected_ans); $i++) {
    array_push($columns, 'q' . $i);
}
$sql = "INSERT INTO MyGuests (username, " . implode(", ", $columns) . ") VALUES (\"" . mysqli_real_escape_string($VALID_USER) . "\", " . implode(", ", $selected_ans) . ")";
$conn->query($sql);
Kita
  • 1,548
  • 14
  • 21