3

once again I have a question for the STACKOVERFLOW hivemind. Here's the deal, I'm trying to insert all of my $_POST data from a form into a mysql table. Before, I did:

    INSERT INTO forms (Place, Date, Find, username, who_sponsored, hours, comments, howdiditgo, studentleader_name, studentleader_email, description)
VALUES ('$place', '$date','$where', '$username', '$who', '$hours', '$comments', '$how', '$description',)");

where all the $values were declared as $_POST['Place'], $_POST['Date'], etc. Now, every time I add a new part to the form (like another textarea or something), I want to just have to create a new column in mysql instead of adding another $_POST['foo']. Here's what I have tried doing:

// In the previous form, I have set all input ids to "service[]", so all this data would be in a more specific array than just $POST.  Turns out all the $_POST['service'] stuff is null...  Here's an example: <input name="placeofservice" type="text" id="service[]">


$forms = serialize($_POST['service']);
var_dump($forms);

mysql_query("INSERT INTO forms VALUES('$forms')")
 or die(mysql_error()); 

The error I keep receiving is: Column count doesn't match value count at row 1. I realize this means that I am trying to put too much data into the database, because there are not enough columns to fit the data. I've checked back and forth to see if I have it right (which, I think I do). For Reference, here's my code for both the form and mysql table:

<form name="form1" method="post" action="process_form.php">
Place of Service</br>
<input name="placeofservice" type="text" id="service[]"></br>

Date of Service</br>
<input name="dateofservice" type="text" id="service[]"></br>

Where did you find this opportunity?</br>
<input name="where" type="text" id="service[]"></br>

What organization sponsored this opportunity?</br>
<input name="who_sponsored" type="text" id="service[]"></br>

How many hours did you work?</br>
<input name="hours" type="text" id="service[]"></br>

How did it go?</br>
<input type="text" id="service[]" name="howdiditgo" maxlength="100" /></br>

Description of Service:
<textarea name="description" id="service[]" COLS=40 ROWS=6></textarea></br>

Comments:
<textarea name="comments" id="service[]" COLS=40 ROWS=6></textarea></br>

Student Leader Name (If Applicable)</br>
<input name="studentleader_name" type="text" id="service[]"></br>

Student Leader Email(If Applicable)</br>
<input name="studentleader_email" type="text" id="service[]"></br>
<input type="submit" name="Submit" value="Submit">
</form>

Mysql Table:

Place | Date | Find |form_id | who_sponsored | hours | comments | howdiditgo | description | studentleader_name | studentleader_email | username

NOTE: I plan to sanitize my DB contents/$POST data as well, but for my purposes I left it out! If you have any questions feel free to ask and I'll post here with EDIT: tags :)

Patrick C
  • 739
  • 3
  • 12
  • 25

5 Answers5

16

My function for this:

function i($table, $array) {
  $query = "INSERT INTO ".$table;
  $fis = array(); 
  $vas = array();
  foreach($array as $field=>$val) {
    $fis[] = "`$field`"; //you must verify keys of array outside of function;
                         //unknown keys will cause mysql errors;
                         //there is also sql injection risc;
    $vas[] = "'".mysql_real_escape_string($val)."'";
  }
  $query .= " (".implode(", ", $fis).") VALUES (".implode(", ", $vas).")";
  if (mysql_query($query))
    return mysql_insert_id();
  else return false;
}
Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
6

Don't create a single field for all you data... it negates the entire value in having a database. You lose all the flexibility to search on specific fields (e.g. all records where hours worked is more than 25, or where date of service was 26th July 2010) You could easily write a function that built the insert statement from an array of values similar to the one Riateche has provided.

It could be improved by switching to mysqli and using bind variables.

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

Here's mine:

function incomingdump($array){
    $tablename="incomingdump";

    $currentID = generateID($tablename);

    $query = "INSERT INTO $tablename (ID) VALUES('$currentID');";  
    sendquery($query);
      foreach($array AS $key => $value){

        $query = "ALTER TABLE $tablename ADD `$key` VARCHAR(".strlen($value).");";  
        sendquery($query);
        $query = "ALTER TABLE $tablename MODIFY `$key`VARCHAR(".strlen($value).");";  
        sendquery($query);
        $query = "UPDATE $tablename SET `$key` = '$value' WHERE ID=$currentID";
        sendquery($query);
      }


}
function generateID($tablename){
    $query = "SELECT count(*) FROM $tablename"; 
    $result = sendquery($query);
    $row = mysql_fetch_row($result);
    return $row[0] + 1;

}

sendquery() is just a wrapper for executing a sql statement. Its called like so:

incomingdump($_POST);
john k
  • 6,268
  • 4
  • 55
  • 59
0

Use json_encode($_POST)for saving data into JSON to MySql database

shubomb
  • 672
  • 7
  • 20
-1

Sorry pal, but you have almost everything wrong.

  1. I plan to sanitize my DB contents/$POST data - WRONG
    There is not a thing called sanitization. There is only syntax rules which you shouldn't "plan to use" but obey unconditionally. Or you'll end up with query error much sooner than with scaring SQL injection. And in terms of database, no DB contents nor POST data shouldn't be treated in any special way. It's DB query, not contents you prepare. And not only POST data but any data going to the query. The big difference.
    Also note that mysql_real_escape_string function itself do not "sanitize" anything.
    Comprehensive information on query building rules you can find in this my answer

  2. every time I add a new part to the form - wrong.
    Adding new field to the database shouldn't be such a trivial task, but always exceptional issue. Database should be planned before you started to draw any forms. And, of course, not a mechanism should be invented to automate such a task. Always manually.

  3. $forms = serialize($_POST['service']); - TERRIBLE WRONG idea.
    I wonder how such an idea can ever come. Mysql of course has nothing to do with PHP proprietary serializing format. And, even if it was, - how the database can tell there is ordinal data for single field or serialized row? Weird.

The only sensible point in your question is how to make query building ease.
Here is the function I am using:

function dbSet($fields, $data = array()) {
  if (!$data) $data = &$_POST;
  $set='';
  foreach ($fields as $field) {
    if (isset($data[$field])) {
      $set.="`$field`='".mysql_real_escape_string($data[$field])."', ";
    }
  }
  return substr($set, 0, -2); 
}

this will return you a SET statement, restricted to the previously defined set of fields.
Usage

$fields = explode(" ","name surname lastname address zip fax phone");
$query  = "INSERT INTO $table SET ".dbSet($fields);
$result = mysql_query($query) or trigger_error(mysql_error().$query);

or

$id     = intval($_POST['id']);
$fields = explode(" ","name surname lastname address zip fax phone");
$query  = "UPDATE $table SET ".dbSet($fields)." WHERE id=$id";
$result = mysql_query($query) or trigger_error(mysql_error().$query);

So, in your case you have to add just a single word to the field list

Community
  • 1
  • 1
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • @SkyWookie lol. Try to be less sensitive. There is no arrogance in my answer. You are funny indeed :) – Your Common Sense Jul 27 '10 at 16:37
  • 5
    Even if you didn't mean any arrogance, your general demeanor to someone who is learning PHP is ridiculous. No decent teacher or helper would scream out WRONG every time they saw something that wasn't right or to their liking. "Sorry, pal" didn't help either. – Patrick C Jul 27 '10 at 17:11
  • but I'm sorry, I'm a bit crabby, still morning here ;) – Patrick C Jul 27 '10 at 17:19
  • It's up to you. You can ignore my answer as well. The benefit of this site is to make an answer available to many other people, may be some of them would be less childish and more grateful hopefully. – Your Common Sense Jul 27 '10 at 17:19
  • Right. I'm really grateful for those who decided to help me without telling me everything I did was wrong. – Patrick C Jul 28 '10 at 15:32
  • @SkyWookie what's wrong with telling you everything you did was wrong? If it IS wrong? It's a fact. Don't blame a mirror, pal. You'd better learn from mistakes, not whine on someone who pointed on it. – Your Common Sense Jul 28 '10 at 16:13
  • 3
    You can still point out it's wrong without directly saying "TERRIBLE WRONG" or "WRONG." Doing things like that basically shattered any confidence I had. Even so though, I guess I'm just misinterpreting your help, and for that I apologize. I just can't believe that every time I need to add a form field that I'll have to do it manually; I figured there'd be a better way to do it. – Patrick C Jul 28 '10 at 18:25
  • @SkyWookie there is nothing to do with forms. You re adding another field to database. Database structure is the basement of your application. The main thing. While form is just representation of it. Don't think of it as HTML form. Think of it as a database structure, linked tables. – Your Common Sense Jul 28 '10 at 18:45
  • Well the forms take the $_POST data, and I want to be able to put all of this data into my DB without having to type in more and more items into the VALUES part of it. Once I solidify the final fields of the HTML form I shouldn't have to worry. INSERT INTO forms (Place, Date, Find, etc) VALUES ('$place', '$date','$where', $etc')"); I want to be able to put: INSERT INTO forms [all DB columns] VALUES ([all values in $_POST array]); – Patrick C Jul 28 '10 at 19:27
  • 1
    @SkyWookie this automated approach will lead you to get hacked pretty soon. The only purpose to do it manually is to take full control over query. Post data souldn't be used for the db field names. Despite of possibility to get field names from the database, it's considered bad practice too: some fields shouldn't be allowed to edit etc. Adding just one word to the field list seems a good compromise to me. – Your Common Sense Jul 28 '10 at 19:42
  • 2
    @Col oh okay, I guess I have a lot to learn about DB security then. Thanks a lot for the help, and sorry I took your comments the WRONG way ;) – Patrick C Jul 28 '10 at 19:46