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?

Link to comment
Share on other sites

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')

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.