gpt4 book ai didi

Php 将更多数组保存到 MySQL 中

转载 作者:行者123 更新时间:2023-11-29 03:15:58 25 4
gpt4 key购买 nike

我正在尝试使用 PHP 将数组保存在 MySQL 数据库中。

代码只插入第一行,如果我有一个包含 5 个元素的 array,它只插入第一个元素,其他元素和 4 个元素不会为我保存它们。

谁能告诉我哪里错了?

非常感谢。

<?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);

?>

最佳答案

当您尝试对多个数组执行 count 时:

$len = count($day_array and $nDay_array and $timeOne_array and $timeTwo_array);

导致数组被 bool 值计算,所以最终分配给 $len 的值为 1,这就是为什么循环只执行一次并且只有第一个元素是插入到数据库中。

如果所有数组的长度都相同,你应该只计算其中的一个:

$len = count($day_array)

更好的做法是对它们进行计数,然后为 $len 分配最小值

关于Php 将更多数组保存到 MySQL 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56517680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com