2016-10-15 22 views
0

PDOプリペアドステートメントを使用して単一のクエリで複数の行を挿入したいが空白行を挿入しない。プリペインドステートメントを使用して空白行を挿入せずにMySQLに複数の行を挿入する方法

実は、私はあなたが以下のHTMLで見ることができる私の形の4つの行を持っていると私は一列のみを記入する際には、3空白行も挿入が、私は、任意の空白行

<form method="post"> 
    <table> 
     <tr> 
     <td><input type="text" name="col1"></td> 
     <td><input type="text" name="col2"></td> 
     </tr> 
     <tr> 
     <td><input type="text" name="col1"></td> 
     <td><input type="text" name="col2"></td> 
     </tr> 
     <tr> 
     <td><input type="text" name="col1"></td> 
     <td><input type="text" name="col2"></td> 
     </tr> 
     <tr> 
     <td><input type="text" name="col1"></td> 
     <td><input type="text" name="col2"></td> 
     </tr> 
    </table> 
    </form> 

を挿入するようにしていない私あなたのcol1とcol2には、あなたは、配列を使用する必要があり、複数あるように、コードがこの

$stmt = $pdo->prepare('INSERT INTO foo VALUES(:col1, :col2)'); 
foreach($data as $item) 
{ 
    $stmt->bindValue(':col1', $item[0]); 
    $stmt->bindValue(':col2', $item[1]); 
    $stmt->execute(); 
} 

のようなものであることは...

+1

? – Bhavin

+0

「空」でチェックしてください。 –

+0

@Bhavin私のコード –

答えて

0

私を助けてください:データを変更する必要がありますベース信任状および変更テーブル名。テスト目的私は使用テーブル名testがあります。あなたがこれまでに試してみました何

のindex.php

<?php 
    if(isset($_POST['submit'])){ 
     $dbhost = "localhost"; //Set your hostname 
     $dbname = "dbname";  //set your dbname 
     $dbusername = "root"; //set your db username 
     $dbpassword = "";  //set your db password 
     $link = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbusername,$dbpassword); 

     for ($i=0; $i <count($_POST['col1']) ; $i++) { 
      $rowNum = $i+1; 
      if($_POST['col1'][$i]!='' && $_POST['col2'][$i]!=''){ 
       $statement = $link->prepare("INSERT INTO test(col1, col2) VALUES(:col1, :col2)"); 
       $res = $statement->execute(array(
        "col1" => $_POST['col1'][$i], 
        "col2" => $_POST['col2'][$i], 
       )); 
       if($res) 
        echo "Row no: $rowNum Successfully inserted.<br>"; 
       else 
        echo "Row no: $rowNum Failed to insert.<br>"; 
      }else 
       echo "Row no: $rowNum single or double field empty.<br>"; 
     } 
    } 
?> 

<form method="post"> 
    <table> 
     <tr> 
     <td><input type="text" name="col1[]"></td> 
     <td><input type="text" name="col2[]"></td> 
     </tr> 
     <tr> 
     <td><input type="text" name="col1[]"></td> 
     <td><input type="text" name="col2[]"></td> 
     </tr> 
     <tr> 
     <td><input type="text" name="col1[]"></td> 
     <td><input type="text" name="col2[]"></td> 
     </tr> 
     <tr> 
     <td><input type="text" name="col1[]"></td> 
     <td><input type="text" name="col2[]"></td> 
     </tr> 
     <tr> 
     <td colspan="2"><input type="submit" name="submit" value="submit"></td> 
     </tr> 
    </table> 
</form> 
+0

ありがとう仲間私はそれを試してみようとしています –

+0

私は編集して、今ログを見ることができます。今すぐチェックしてください。 'データベース情報'と 'テーブル名'を変更する必要があります – AHJeebon

+0

ありがとう、それは働いています –

関連する問題