QS Train
QS Train

Reputation: 95

PHP Looping through elements and adding to Database

I don't know if what I'm trying to do is achievable / plausible but I'll ask anyway:

I am building a survey type website and am looking at storing the responses in a MySQL DB. Each response / text field will be a record

The current page that I'm working on has two elements (Answer1 and Answer2).

How can I get the submit to add each answer as a separate line in my DB? eg, 2 separate records, with different text stored in the responsetext field?

I have the below (obviously changed for security reasons), which adds one record, but of the element that I specify:

$conn = new mysqli($dbhost, $dbuser, $dbpass,$dbname);

if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
} 
$stmt = $conn->prepare("INSERT INTO responses (qkey,rtext)
VALUES ('".$_POST["1"]."','".$_POST["Q1Answer"]."')");  

$Q1Answer = $_POST["Q1Answer"];

$stmt->bind_param("s", $Q1Answer);

$stmt->execute();

$stmt->close();   

$conn->close();

I imagine I could loop through all the elements and add them one by one? Is this possible on the submit action / post?

I have searched here but can't find anything that has been able to help...

Upvotes: 0

Views: 95

Answers (2)

Mumtaz Ahmad
Mumtaz Ahmad

Reputation: 442

look at this @K. Tromp

$i = 1;
$queryValue = NULL;
foreach ($_POST as $key => $value) {
    if ($key == $i) {
        $value . $i = mysqli_real_escape_string($value);
    }
    if ($key == 'Q' . $i . 'Answer') {
        $value . $i = mysqli_real_escape_string($value);
    }
    if ($i % 2) {
        $queryValue .= "($key.($i-1), $key.$i),";
    }
    $i++;
}
$query = 'INSERT INTO responses (qkey,rtext) VALUES ' . rtrim($queryValue);
mysqli_query($conn, $query);

Upvotes: 0

K. Tromp
K. Tromp

Reputation: 360

First of all, NEVER use $_POST or $_GET or $_SESSION values in your sql-statement, you should always sanitize with for example:

$value = mysqli_real_escape_string($_POST['value1']);

This is to prevent any mysql injections just like OldPadawan mentions..

To answer your question you could use a for loop:

$i = 1;
foreach ( $_POST as $key => $value ){
    if ( $key == $i ){
        $value.$i = mysqli_real_escape_string($value);
     }
     if ( $key == 'Q'.$i.'Answer' ){
        $value.$i = mysqli_real_escape_string($value);
     }
    if ( $i % 2 ){
        mysqli_query($conn, "INSERT INTO responses (qkey,rtext) VALUES ($key.($i-1), $key.$i)");
    }
$i++;
 }

Upvotes: 2

Related Questions