Jump to content

[SOLVED] Inserting large amounts of form data?


anya7

Recommended Posts

This is probably a really dumb question, but I certainly do not profess to be an expert in PHP or MySQL...

 

I have a form where the data gets stored in a database when the form is submitted.  As far as I know, the procedure for doing this is something like:

 

$_POST['firstname'] = $firstname;
$_POST['lastname'] = $lastname;
$_POST['email'] = $email;

$result = mysql_query("INSERT INTO members (firstname, lastname, email) VALUES ('$firstname', '$lastname', '$email')");

 

where you have to assign all the $_POST values to a new variable, individually, and then insert them into the database, individually.  Which is ok if you have a small amount of form fields, but the form I'm working on now has about 150 fields...that obviously gets tedious really fast.  Is there any better/easier way to do this?

It's like this $firstname = $_POST['firstname']; and not as you show it.

 

However, if you create the post form "name" values to exactly match the names you call your columns in the table, then you can do something like this:

 

<?php

// Just emulating a post form submission
$_POST['firstname'] = 'Brian';
$_POST['lastname'] = "O'rielly";
$_POST['submit'] = 1;


$arrPost = $_POST;
unset($arrPost['submit']); // Remove non-columns from post data
$arrPost = array_map('addslashes', $arrPost);  // Backslash any quotes

// Build the query
$strInsertQuery = sprintf(  'INSERT INTO `members` (%s) VALUES (%s)'
                          , '`' . join('`,`', array_keys($arrPost)) . '`'
                          , "'" . join("','", array_values($arrPost)) . "'"
                         );
                               
echo $strInsertQuery; // For debug purposes

$result = mysql_query($strInsertQuery);

?>

 

The echo from the above code would output something like this:

 

INSERT INTO `members` (`firstname`,`lastname`) VALUES ('Brian','O\'rielly')

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.