[英]INSERT multiple select arrays with prepared statements
My DB contains a table called 'opening_days_hours': 我的数据库包含一个名为“ opening_days_hours”的表:
CREATE TABLE IF NOT EXISTS opening_days_hours (
ID_OpeningHours bigint(20) NOT NULL AUTO_INCREMENT,
ID_Address bigint(20) NOT NULL,
opening time NOT NULL,
closing time NOT NULL,
day int(11) NOT NULL DEFAULT 0,
INDEX (ID_Address),
PRIMARY KEY (ID_OpeningHours),
CONSTRAINT FK_Addresses_OpeningHours
FOREIGN KEY (ID_Address) REFERENCES addresses(ID_Address)
ON DELETE CASCADE) ENGINE=InnoDB
Each day contains one and only one 'opening' and 'closing' time. 每天只有一个“开放”和“关闭”时间。
The 'day' column value is obtained from a 'checkbox' value as 从“复选框”值中获取“天”列值,如下所示:
<input type="checkbox" id="sun" name="days[]" "<?php if (isset($days) && $days=="days") echo "checked"; ?>" value="1">
...same for mon, tue, wed, etc.
whereas the times are passed by the user via a 'select' statement (dropdown). 而时间是由用户通过“选择”语句(下拉菜单)传递的。
Everything works fine if 'opening' and 'closing' are scalars (1 value) and 'day' is an array defined as 'days[]'. 如果“打开”和“关闭”是标量(1值),并且“天”是定义为“天[]”的数组,则一切工作正常。 For this, I use a prepared statement as:
为此,我将准备好的语句用作:
$q = "INSERT INTO opening_days_hours
day,
opening,
closing
ID_Address
) VALUES (?, ?, ?, ?)";
$days = array();
if(isset($_POST['days'])) {
$days = $_POST['days'];
}
mysqli_stmt_bind_param($stmt, 'issi',
$days,
$opening,
$closing,
$ID_Address
);
foreach ($days as $one) {
mysqli_stmt_execute($stmt);
}
With this code I can store one day per row in the column called 'day' and and the values of $opening and $closing being the same for every day. 使用此代码,我可以将每行一天存储在名为“ day”的列中,并且$ opening和$ closing的值每天相同。
HOWEVER, when 'opening' and 'closing' are themselves arrays, just like 'day', I obtained a mysqli_stmt_execute error ('Array to string conversion') and nothing is hence stored to the DB. 但是,当“ opening”和“ closing”本身是数组时,就像“ day”一样,我遇到了mysqli_stmt_execute错误(“ Array to string conversion”),因此没有任何内容存储到数据库中。
I did a lot of tests with different constructions of the code. 我用不同的代码结构做了很多测试。 I diagnosed the problem being that I cannot pass mysqli_stm_execute($stmt) more than one array.
我诊断出问题是我不能传递mysqli_stm_execute($ stmt)多个数组。 I ran out of options on how to solve this problem.
我没有解决该问题的选择。
All the solutions I found so far store many values in the same row, but I don't want that. 到目前为止,我发现的所有解决方案都将许多值存储在同一行中,但我不希望这样。 I actually need to store one opening time and one closing time per each day, and store each day in its own row.
实际上,我每天需要存储一个打开时间和一个关闭时间,并将每一天存储在自己的行中。
I hope the issue is clear. 我希望问题清楚。
SOLVED: 解决了:
I had to loop the binding: 我必须循环绑定:
for ($i = 0; $i < count($days); ++$i)
{
mysqli_stmt_bind_param($stmt, "issi",
$days[$i],
$opening[$i],
$closing[$i],
$ID_Address
);
mysqli_stmt_execute($stmt);
}
as explained in this previous stackoverflow explanation 如之前的stackoverflow说明中所述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.