[英]How to insert array result into mysql using prepared statement in PHP
我習慣使用prepared語句將記錄插入mysql,對於非數組值,下面的代碼很好,但是對於張貼的數組類型,它給我錯誤:
數組到字符串的轉換
的index.php
<input type="text" name="test[]" />
<input type="text" name="test1[]" />
輸出
[test] => Array ( [0] => 1 ) [test1] => Array ( [0] => 2 )
PHP插入(發布的數據在數組中)
$test=array_map('trim',$_POST["test"]);
$test1=array_map('trim',$_POST["test1"]);
$stmt = $conn->prepare("INSERT INTO test(v1,v2) VALUES (?,?)");
stmt->bind_param("ss",$test,$test1)
stmt->execute();
現在,請幫助如何使用准備好的語句將數組數據發布的html表單插入mysql。 以后我需要使用准備好的語句記錄多行。 謝謝
嘗試這個:
$test=array_map('trim',$_POST["test"]);
$test1=array_map('trim',$_POST["test1"]);
$stmt = $conn->prepare("INSERT INTO test(v1,v2) VALUES (?,?)");
$error=false;
foreach($test AS $key=>$value){
if(! stmt->execute([$value,$test1[$key]])){
$error=true;
break;
}
}
if($error) // handle error
在這樣的循環中運行查詢是准備好的語句的目的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.