0

ユーザーがクラスとアクティビティを複数のフィールドに入力できるフォームがあります。これらのフィールドは次のように宣言されています。

    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に少し慣れていないので、これを難しい方法でやっているのではないかと心配しています。

ご不明な点がございましたら、お気軽にお問い合わせください。

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など)を使用するか、入力を適切にサニタイズするようにしてください。

また、この解決策は私の提案であり、それを行うための多くの方法の1つです。しかしねえ、あなたは意見を求めました:) PHPは非常に柔軟な言語なので、物事を成し遂げるのは簡単ですが、それを成し遂げる方法はたくさんあるので、常に醜いものを選ぶ機会があります。他の、特に強い型の言語は、設計上それを妨げる可能性があります。しかし、PHPは本当に簡単に習得でき、コードは徐々に改善されると確信しています:)

私が気付いたもう1つのことは、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">

次のステップでは、コードを少しリファクタリングして、さらに構造化されて読みやすくすることができます。「テーブルに何かを挿入する」という1つのタスクを2回実行しているので、それから再利用可能な関数を作成することもできます。

<?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 に答える