PDOプリペアドステートメントを使用して単一のクエリで複数の行を挿入したいのですが、空白行を挿入したくありません。
実際、以下のHTMLで確認できるフォームに4つの行があり、1つの行だけを入力すると、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>
私のコードはこんな感じです
$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();
}
お願い助けて...
col1とcol2は複数あるため、配列を使用する必要があります。データベースのクレデンシャルを変更し、テーブル名を変更する必要があります。テスト目的私はテーブル名を使用しています
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>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加