SmashCode
SmashCode

Reputation: 4257

Passing an array via POST in PHP to be inserted into MySQL

I have a form that allows users to input classes and activities into multiple fields, these fields are declared like this :

    label for ="classact">Classes and Activities</label>
        <input type = "text" name = "classact[0]" value ="" id ="classact[0]">
        <input type = "text" name = "classact[1]" value ="" id ="classact[1]">
        <input type = "text" name = "classact[2]" value ="" id ="classact[2]">

When the form is passed this is the code that handles in the insert:

    $maininsert = "INSERT INTO `camptest`
        (`name`, `city`, `phone`, `photo`)
        VALUES
        ('$_POST[name]', '$_POST[city]', '$_POST[phone]', '$photoinfo')
        SET @lid = LAST_INSERT_ID()
        ";

    $classactinsert = "INSERT INTO `class_act`
                (`cid`";

    for($i = 0; $i < 3; $i++)
    {
       if(isset($_POST['classact'][$i]))
       {
          $temp = $i+1; 
          $classactinsert = $classactinsert . ",`act$temp`";
       }
    }

   $classactinsert = $classactinsert . ")
                                VALUES
                                ('@lid'";

   for($i = 0; $i < 3; $i++)
   {
      if(isset($_POST['classact'][$i]))
      {
         $classactinsert = $classactinsert . ",'$_POST[classact][$i]";
      }
   }

  $classactinsert = $classactinsert . ")";                                  

  $indata = $maininsert . $classactinsert;

  $result = mysql_query($indata);

I realize thats alot of code, but upon filling out the form and submitting this is the query that gets generated:

    INSERT INTO `camptest` (`name`, `city`, `phone`, `photo`) VALUES ('Multiple Activities', 'Nowhere', '555-555-1111', 'images/51127f6b06d1e.jpg') SET @lid = LAST_INSERT_ID() INSERT INTO `class_act` (`cid`,`act1`,`act2`,`act3`) VALUES ('@lid','Array[0],'Array[1],'Array[2])

The query is not inserting, but its not throwing back any errors either, even though I have them turned on.

My main question is, what am I doing wrong that is causing the values to act1, act2, and act3 to show up as Array[0], Array[1], and Array[2]?

My secondary question is, am I even going about this the right way? I'm a little new to php and I'm afraid I might be doing this the hard way?

Any help would be appreciated, let me know if you need any additional information.

Upvotes: 0

Views: 6880

Answers (1)

Quasdunk
Quasdunk

Reputation: 15220

It does not insert anything, because (among other things) your query string is not being built correctly.

('@lid','Array[0],'Array[1],'Array[2])

The apostrophes are messed up. I'd like to suggest a (in my opinion) cleaner and more structured way to perform your task:

Note: You are obviously working with the mysql_*-stack, so my example is also based on it. But be aware that this is deprecated. Please use mysqli or even better: PDO instead.

<?php

$maininsert = "INSERT INTO `camptest`
              (`name`, `city`, `phone`, `photo`)
              VALUES
              ('{$_POST['name']}', '{$_POST['city']}', '{$_POST['phone']}', '$photoinfo')";

//perform the main insert and fetch the insert id
mysql_query($maininsert);

$last_id = mysql_insert_id();

// Put the keys and values of the acts in arrays. We can already 
// populate them with the one key-value-pair we already know
$act_keys = array('cid');
$act_values = array($last_id);

foreach($_POST['classact'] as $key => $value) {
  //walk through the POSTed acts and add them to the corresponding array
  $act_keys[] = 'act'.($key+1);
  $act_values[] = $value;
}

//Now build the whole string:
$insert_acts = "INSERT INTO `class_act` 
               (`" . implode("`, `", $act_keys) . "`) 
               VALUES 
               ('" . implode("', '", $act_values) . "')";

//and finally perform the query:
mysql_query($insert_acts);

Please also note that this code is highly vulnerable concerning SQL-Injection and should absolutely not be used in production!!! Make sure to either use prepared statements (like with PDO) or/and to sanitize your input properly.

Also, this solution is just my suggestion and one of many ways to do it. But hey, you asked for an opinion :) PHP is very flexible language, so it's easy to get stuff done, but there are many ways to get it done, so there are always chances to pick a hard an ugly one. Other, especially strong typed languages might prevent that by design. But PHP is really easy to learn and I'm sure your code will improve gradually :)

Another thing I've noticed: You don't need to specify the array-keys in your HTML, you just need to make clear that it's an array with [] behind the name. Also, I'm not sure if the id-attributes you using are valid, but you might want use something more simple:

<input type="text" name="classact[]" value="" id="classact1">
<input type="text" name="classact[]" value="" id="classact2">
<input type="text" name="classact[]" value="" id="classact3">

In the next step, you might want to refactor your code a little to make it even more structured and readable. Since you are performing one task, which is 'inserting something into a table', twice, we could also make a resusable function out of it:

<?php 

function my_insert($table, $data) {
  // We leverage the flexibility of associative arrays
  $keys   = "`" . implode("`, `", array_keys($data)) . "`";
  $values = "'" . implode("', '", $data) . "'";

  mysql_query("INSERT INTO `{$table}` ({$keys}) VALUES ({$values})");

  return mysql_insert_id(); //This might come in handy...
}

//in order to use this function, we now put our data into associative arrays:
$class_insert = array(
  'name'  => $_POST['name'],
  'city'  => $_POST['city'],
  'phone' => $_POST['phone'],
  'photo' => $photoinfo
);

$class_insert_id = my_insert('camptest', $class_insert); //and pass it to the function

// You can either build the array while looping through the POSTed values like above, 
// or you can pass them in directly, if you know that there will always be 3 values:
$activities_insert = array(
  'cid'  => $class_insert_id,
  'act1' => $_POST['classact'][0],
  'act2' => $_POST['classact'][1],
  'act3' => $_POST['classact'][2]
); 

$activities_insert_id = my_insert('class_act', $activities_insert);

There sure is enough room for improvement and optimization - just wanted to show you how awesome PHP can be :-P

Upvotes: 2

Related Questions