通过PHP中的POST传递数组以插入MySQL

时间:2013-02-06 16:19:43

标签: php mysql post

我有一个表单,允许用户将类和活动输入到多个字段中,这些字段声明如下:

    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]">

传递表单时,这是插入中处理的代码:

    $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);

我意识到很多代码,但在填写表单并提交时,会生成查询:

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

查询没有插入,但它也没有丢弃任何错误,即使我已经打开它们。

我的主要问题是,我做错了什么导致act1,act2和act3的值显示为Array [0],Array [1]和Array [2]?

我的第二个问题是,我是否正确地采取了这种方式?我对php有点新鲜,我担心我可能会这么做吗?

任何帮助将不胜感激,如果您需要任何其他信息,请告诉我们。

1 个答案:

答案 0 :(得分:2)

它不会插入任何内容,因为(除其他外)您的查询字符串未正确构建。

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

撇号搞砸了。我想建议(在我看来)更清洁,更有条理的方式来执行你的任务:

注意:您显然正在使用mysql _ * - stack,所以我的示例也基于它。但请注意,这已被弃用。请使用mysqli甚至更好:PDO代替。

<?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);

另请注意,此代码在SQL-Injection方面非常容易受到攻击,绝对不能用于生产!确保使用预准备语句(如PDO)或/并正确清理输入。

此外,这个解决方案只是我的建议和许多方法之一。但是,嘿,你问了一个意见:) PHP是非常灵活的语言,因此很容易完成任务,但有很多方法可以完成它,所以总有机会挑选一个一个丑陋的人。其他,特别是强类型语言可能会在设计上阻止这种情况。但PHP非常容易学习,我确信你的代码会逐渐改进:)

我注意到的另一件事:你不需要在HTML中指定数组键,你只需要清楚它是一个名称后面带有[]的数组。此外,我不确定您使用的id - 属性是否有效,但您可能希望使用更简单的内容:

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

在下一步中,您可能希望稍微重构一下代码,使其更具结构性和可读性。由于您正在执行一项任务,即“将某些内容插入表格中”,两次,我们还可以从中创建一个可重复使用的功能:

<?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);

确实有足够的改进和优化空间 - 只是想向您展示PHP有多棒:-P