gpt4 book ai didi

php foreach 与 sql

转载 作者:行者123 更新时间:2023-11-29 13:19:00 25 4
gpt4 key购买 nike

我有一个名为“questions”的数组,我正在尝试使用 foreach 将其插入到 mysql 中。数组看起来像这样:

    Array
(
[0] => Array
(
[booking_id] => 936
[question_id] => a
[value] => 4
)

[1] => Array
(
[booking_id] => 936
[question_id] => b
[value] => 3
)

[2] => Array
(
[booking_id] => 936
[question_id] => c
[value] => 2
)

[3] => Array
(
[booking_id] => 936
[question_id] => d
[value] => 1
)
)

FOREACH 看起来像这样:

$sql = array(); 
foreach( $_POST['questions'] as $row ) {

$sql[] = '("'.$row['booking_id'].'", "'.$row['question_id'].'", '.$row['value'].')';
}

mysql_query('INSERT INTO table (booking_id, question_id, value) VALUES '.implode(',', $sql));

foreach 只是将数组中的第一项插入表中,并不循环遍历整个数组。

有什么想法我哪里出错了吗?

最佳答案

现在已经可以在 PHP 中使用 PDO 或 MySQLi 了。这是一个工作示例。您可以将 $arr 替换为 $_POST 并进行一些重构以满足您的需求。

$mysqli = new mysqli('localhost', 'root', '', 'dachi');

if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$arr = array(
array(
'booking_id' => 936,
'question_id' => 15,
'value' => 4,
),
array(
'booking_id' => 936,
'question_id' => 15,
'value' => 3,
),
);

foreach ($arr as $rec) {
$stmt = $mysqli->prepare("INSERT INTO `test` (`booking_id`,`question_id`,`value`) VALUES (?,?,?)");
// You will probably need to change 'iii'
// i = integer
// s = string
// So you might have something like isi if you need like that or sss
$stmt->bind_param('iii', $rec['booking_id'], $rec['question_id'], $rec['value']);
$d = $stmt->execute();
$stmt->close();
}

关于php foreach 与 sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21105716/

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