0

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.

4

1 回答 1

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 注入方面极易受到攻击,绝对不应在生产中使用!!!确保使用准备好的语句(如 PDO)或/和正确清理您的输入。

此外,此解决方案只是我的建议,也是众多方法之一。但是,嘿,您征求意见 :) PHP 是一种非常灵活的语言,所以很容易完成工作,但是有很多方法可以完成,所以总是有机会选择一个难看的难的。其他,特别是强类型语言可能会通过设计阻止这种情况。但是 PHP 真的很容易学习,我相信你的代码会逐渐改进 :)

我注意到的另一件事:您不需要在 HTML 中指定数组键,您只需要明确它是一个[]名称后面的数组。另外,我不确定id您使用的 -attributes 是否有效,但您可能想要使用更简单的东西:

<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

于 2013-02-06T17:46:00.540 回答