1

I just learned how to Foreach value from POST from form:

foreach($_POST as $key => $value) {
  echo "POST parameter '$key' has '$value'";
}

But my question is how to insert those data: $key $value to the mysql database.Can I just do like this :

mysqli_query($con,"INSERT INTO tableName $key $value)
3
  • you have to see with INSERT BATCH for this. Commented Jun 21, 2017 at 17:14
  • is your $key equivalent to your SQL column name? Commented Jun 21, 2017 at 17:34
  • yes,my $key equivalent to my SQL column name. Commented Jun 21, 2017 at 17:36

2 Answers 2

1
// Not sure how you handled your sql connexion, so I wrote a short example
$linkDB=new mysqli('localhost', 'user', 'pwd', 'db_name');
if($connectDB->connect_error) {
    die('Erreur de connexion ('.$connectDB->connect_errno.'): '.$linkDB->connect_error);
    exit();
}
$linkDB->set_charset('utf-8');

foreach($_POST as $key=>$value) {
    /* Just to be safe, I suggest to manually escape the key,
     * to avoid injections. Someone correct me if it's wrong.
     */
    $key=mysqli_real_escape_string($linkDB, $key);
    $stmt=$linkDB->prepare(/** @lang MySQL */
        "INSERT INTO `tablename` (`$key`)
        VALUES (?)");
    $stmt->bind_param('s', $value);
    if($stmt !== false) {
        $stmt->execute();
    }
    $stmt->close();
}
$linkDB->close();

In case you want to use all key/values in the post in one query, then do like this instead.

$queryCols="";
$queryVals="";
foreach($_POST as $key=>$value) {
    $queryCols.="`".mysqli_real_escape_string($linkDB, $key)."`,";
    $queryVals.="'".mysqli_real_escape_string($linkDB, $value)."',";
}
$queryCols=preg_replace("/(,)$/", "", $queryCols);
$queryVals=preg_replace("/(,)$/", "", $queryVals);
$stmt=$linkDB->prepare(/** @lang MySQL */
    "INSERT INTO `tablename` ($queryCols)
    VALUES ($queryVals)");
if($stmt !== false) {
    $stmt->execute;
}
$stmt->close();
$linkDB->close();

Something like this should do the trick... ;)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much !I'll try!
1

Create the sql insert query from array values,See the below Example

$ins_clm = "";
$ins_val = "";
foreach($_POST as $key => $value) {
  echo "POST parameter '$key' has '$value'";
   $ins_clm .= $key.","; 
   $ins_val .= "'".$value."',";


}
   $ins_clm = substr($ins_clm ,0,strlen($ins_clm )-1);
   $ins_val = substr($ins_val ,0,strlen($ins_val )-1);

  $ins_query = "insert into table ($ins_clm) values ($ins_val)";


   $r = mysqli_query($dbc,$ins_query);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.