gpt4 book ai didi

php mysql 准备语句循环数组

转载 作者:行者123 更新时间:2023-11-29 20:46:45 24 4
gpt4 key购买 nike

我的问题是我想循环遍历一个数组并将该数组的每个条目插入到 mySQL 表的另一列中。老实说,我不确定这是否是设计数据库的最佳方式,但这是我可以想象的一种方式,它有效。如果有人更好地了解如何做到这一点或最佳实践的链接或其他内容,那就太棒了。

所以我想做的是:我有一个表格,人们可以在其中注册以提供送餐服务。他可以输入姓名等以及最多 10 个报价(数据库表的限制)。这些信息应插入表“anbieter”中的字段“angebot_0”、“angebot_1”...所以我所做的是:

if (isset($_POST['register_offer']) and isset($_POST['anbieter-email'])){

$name = $loc = $cat = $email = $password ="";
$angebot = array();
// fill all variables
$name = test_sql($_POST['anbieter-name']);
$email = test_sql($_POST['anbieter-email']);
$password = test_sql($_POST['anbieter-password']);
$loc = test_sql($_POST['anbieter-loc']);
$cat = test_sql($_POST['anbieter-cat']);
// fill $angebot with all given angebot[] entries
foreach($_POST['angebot'] as $ang) {
$angebot[] = test_sql($ang);
}

if(!empty($name) and !empty($loc) and !empty($email) ){
/* decrypt password */
$password = password_hash($password, PASSWORD_BCRYPT, ["cost" => 12]);
// insert name, email, password, location and category into database
/* Prepared statement, stage 1: prepare */
if (!($stmt = $conn->prepare("INSERT INTO anbieter (anbieter_name, anbieter_email, anbieter_password, anbieter_loc, anbieter_cat) VALUES (?, ?, ?, ?, ?)"))) {
echo "Prepare failed: (" . $stmt->errno . ") " . $stmt->error;
}
/* Prepared statement, stage 2: bind and execute */
if (!$stmt->bind_param('sssss', $name, $email, $password, $loc, $cat)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

$userid = $stmt->insert_id;
// safe all angebot[] entries to database - angebot[0]-> angebot_0
for($x=0; $x < count($angebot) ; $x++) {
$upd = $conn->prepare("UPDATE anbieter SET angebot_".$x." = ? WHERE abieter_ID = ? ");
$upd->bind_param('si', $angebot[$x], $userid);
$upd->execute();
}

所以当我这样做时,我收到错误:

Fatal error: Call to a member function bind_param() on boolean in ...

使用 $x 来命名表的不同字段是一种非常糟糕的方法,但这是我能想到的唯一可行的方法:/

我希望有人能帮助我! :)非常感谢!

最佳答案

我的建议是,您可以在单个查询中多次执行单个记录更新查询,

例如:

$query = "UPDATE anbieter SET";
for ($x = 0; $x < count($angebot); $x++) {
$query .= " angebot_" . $x . " = '" . $angebot[$x] . "', ";
}
echo $query .= " WHERE abieter_ID = " . $userid;

关于php mysql 准备语句循环数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38394020/

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