ここに同様の質問がありますが、実際には答えがわかりません:
PHP + PDO: Bind null if param is empty
バインドされた変数のみを変更して、ステートメントをループで処理する必要があります。
お気に入り:
$this->array = array(
"cell1" => "",
"cell2" => "",
);
$this->sth = $db->prepare("INSERT INTO `table`
(`coloumn1`, `coloumn2`)
VALUES (:coloumn1, :coloumn2)");
$this->sth->bindParam(:coloumn1, $this->array['cell1'], PDO::PARAM_STR);
$this->sth->bindParam(:coloumn2, $this->array['cell2'], PDO::PARAM_STR);
//Data proccessing...
foreach($data as $value){
$this->array['cell1'] = $value['cell1'];
$this->array['cell2'] = $value['cell2'];
try {
this->sth->execute();
print_r($this->sth->errorInfo());
}
catch(PDOException $e){
echo 'sh*t!';
}
}
いずれかの値が空の文字列になるまで、すべてがうまく機能します。私の問題は、「cell1」が空の文字列で、バインドされたパラメーターが null 参照であり、機能しない場合です。しかし、ループのために参照されたバインディングが必要なので、bindValue は解決策ではありません。
そして、処理したいデータが膨大なため、ループが非常に必要です。
なにか提案を?
実行する直前に試しました:
foreach($this->array as $value){
if(!$value) {
$value = "";
}
}
うまくいきません。私の問題を解決した唯一の方法は、これに変更することです:
$this->array['cell1'] = !empty($value['cell1']) ? $value['cell1'] : "";
$this->array['cell2'] = !empty($value['cell2']) ? $value['cell2'] : "";
しかし、これはあまりにも粗末なようです...