我正在尝试使用MySQL
将数组保存在PHP
数据库中。
代码仅插入第一行,如果我有一个由5个元素组成的array
,它只会插入第一个元素,而其他四个则不会为我保存。
谁能告诉我我哪里错了?
非常感谢。
<?php
//getting user values
$day = $_POST['Day'];
$nDay = $_POST['n_Day'];
$fieldOne = $_POST['Field_one'];
$fieldTwo = $_POST['Field_two'];
$timeOne = $_POST['Time_one'];
$timeTwo = $_POST['Time_two'];
$idR = $_POST['id_ristorante'];
$day_array = explode(",",$day);
$nDay_array = explode(",",$nDay);
$timeOne_array = explode(",",$timeOne);
$timeTwo_array = explode(",",$timeTwo);
$len = count($day_array and $nDay_array and $timeOne_array and $timeTwo_array);
$output=array();
//require database
require_once('db.php');
//checking if email exists
$conn=$dbh->prepare('SELECT id_ristorante FROM Orari WHERE id_ristorante=:idR');
$conn->bindParam(':idR', $idR, PDO::PARAM_STR);
$conn->execute();
//results
if($conn->rowCount() !==0){
$output['isSuccess'] = 0;
$output['message'] = "Orario già inserito";
} else {
for($i=0;$i<$len;$i++){
$day = $day_array[$i];
$nDay = $nDay_array[$i];
$timeOne = $timeOne_array[$i];
$timeTwo = $timeTwo_array[$i];
$conn=$dbh->prepare('INSERT INTO Orari (Day, n_Day, Field_one, Field_two, Time_one, Time_two, id_ristorante) VALUES (?,?,?,?,?,?,?)');
//encrypting the password
$conn->bindParam(1,$day);
$conn->bindParam(2,$nDay);
$conn->bindParam(3,$fieldOne);
$conn->bindParam(4,$fieldTwo);
$conn->bindParam(5,$timeOne);
$conn->bindParam(6,$timeTwo);
$conn->bindParam(7,$idR);
$conn->execute();
if($conn->rowCount() == 0) {
$output['isSuccess'] = 0;
$output['message'] = "Errore, riprova.";
} elseif($conn->rowCount() !==0){
$output['isSuccess'] = 1;
$output['message'] = "Orari salvati!";
}
}
}
echo json_encode($output);
?>
答案 0 :(得分:0)
当您尝试对多个数组进行count
时:
$len = count($day_array and $nDay_array and $timeOne_array and $timeTwo_array);
and
导致对数组进行布尔计算,因此最终分配给$len
的值为1,这就是为什么循环仅执行一次且仅将第一个元素插入DB的原因。
如果所有数组都具有相同的长度,则应该仅依靠其中之一进行计数:
$len = count($day_array)
更好的做法是先对它们进行计数,然后为$len
分配最小值
答案 1 :(得分:0)
更改此行
$len = count($day_array and $nDay_array and $timeOne_array and $timeTwo_array);
收件人
$len = count($day_array) + count($nDay_array) + count($timeOne_array) + count($timeTwo_array);