PHP中如何遍历数组并将数据保存至数据库?
问题分析与解决:批量投标数据插入错误处理
问题描述
从数据库查询BidTables表,每行末尾添加输入框让用户更新投标价格,提交时遇到两类错误:
- 初始代码报错:
Fatal error: Uncaught Error: Object of class mysqli_result could not be converted to string in... - 改用预处理语句后报错:
Warning: Array to string conversion in...
初始处理代码
<?php if (isset($_POST['save'])){ if(!empty($_POST['newbid'])) { $biduserID = $_SESSION['id']; $itemID = $_GET['ItemId']; $bidprice = ($_POST['newbid']); $getcurrentround = "SELECT `Round` FROM `RoundCounter` WHERE `ItemID` =".$_GET['ItemId'].""; $currentroundresult= $db->query($getcurrentround); $currentround = $currentroundresult->fetch_assoc(); $currentround1 = $currentround['Round']; $biddername = $_SESSION["id"]; $count = $_POST['count']; $newbid = $_POST['newbid']; // check empty and check if interger print_r($newbid); $getusername = "SELECT `Username` FROM `User` WHERE `UserID` = `$biddername`"; $username1= $db->query($getusername); $getbandname = "SELECT `BandName` FROM `BidTables` WHERE `ItemID` =" .$_GET['ItemId'].""; $bandname= $db->query($getbandname); $getnumberlots = "SELECT numberlots FROM `Item` WHERE `ItemID` =".$_GET['ItemId'].""; $numberlots= $db->query($getnumberlots); $bid = 1; foreach($_POST as $bid => $value) { $sql4 = "INSERT INTO BidTables (`BandName`,`BidderID`, `ItemID`, `BidPrice`, `Round`, `Username`) VALUES (?,?,?,?,?,?)"; $stmt = $db->prepare($sql4); echo $db->error; $stmt->bind_param("siiiis", $bandname, $biduserID, $itemID, $bid ,$currentround1, $username1 ); $stmt->execute(); } } ?>
表格与提交按钮代码
<form action="" method="POST"> <table class="table table-hover"> <thead class="thead"> <tr class="header"> <th>ID</th> <th>Band</th> <th>Current Price</th> </tr> <?php $sql = "SELECT * FROM BidTables WHERE ItemID = ".$_GET['ItemId']." ORDER BY `Round` DESC"; $resultSQL= mysqli_query($db, $sql); if(mysqli_num_rows($resultSQL) > 0){ } ?> </thead> <tbody> <!-- PHP CODE TO FETCH DATA FROM ROWS --> <tr> <?php // LOOP TILL END OF DATA while($row = $resultSQL->fetch_assoc()) { ?> <tr> <td><?=$row['bidtable']?></td> <td><?=$row['BandName']?></td> <td><?=$row['BidPrice']?></td> <td><input type="number" name="newbid[]" size="10" /></td> </tr> <?php } ?> </table> <input type="hidden" name="count" value="<?=$resultSQL->num_rows?>" /> <button class="btn btn-primary btn-lg" name="save">Submit</button> </form>
编辑后预处理语句代码
<?php if (isset($_POST['save'])){ if(!empty($_POST['newbid'])) { $biduserID = $_SESSION['id']; $itemID = $_GET['ItemId']; $bidprice = ($_POST['newbid']); $count = $_POST['count']; $newbid = $_POST['newbid']; // check empty and check if interger print_r($newbid); $sql6 = "SELECT `Round` FROM `RoundCounter` WHERE `ItemID` =?"; // SQL with parameters $stmt6 = $db->prepare($sql6); $stmt6->bind_param("i", $itemID); $stmt6->execute(); $result6 = $stmt6->get_result(); // get the mysqli result $round = $result6->fetch_assoc(); // fetch data $sql7 = "SELECT `Username` FROM `User` WHERE `UserID` = ?"; // SQL with parameters $stmt7 = $db->prepare($sql7); $stmt7->bind_param("i", $biduserID); $stmt7->execute(); $result7 = $stmt7->get_result(); // get the mysqli result $username = $result7->fetch_assoc(); // fetch data $sql8 = "SELECT `BandName` FROM `BidTables` WHERE `ItemID` =?"; // SQL with parameters $stmt8 = $db->prepare($sql8); $stmt8->bind_param("i", $itemID); $stmt8->execute(); $result8 = $stmt8->get_result(); // get the mysqli result $bandname = $result8->fetch_assoc(); // fetch data $sql9 = "SELECT numberlots FROM `Item` WHERE `ItemID` =?"; // SQL with parameters $stmt9 = $db->prepare($sql9); $stmt9->bind_param("i", $itemID); $stmt9->execute(); $result9 = $stmt9->get_result(); // get the mysqli result $numberlots = $result9->fetch_assoc(); // fetch data foreach($_POST as $bid => $value) { $sql4 = "INSERT INTO BidTables (`BandName`,`BidderID`, `ItemID`, `BidPrice`, `Round`, `Username`) VALUES (?,?,?,?,?,?)"; $stmt = $db->prepare($sql4); echo $db->error; $stmt->bind_param("siiiis", $bandname, $biduserID, $itemID, $bid ,$round, $username ); $stmt->execute(); } } } ?>
错误原因与修复方案
错误根源
- mysqli_result对象直接使用:初始代码中
$username1 = $db->query($getusername);返回的是结果对象,不是字符串值,直接绑定到预处理参数会触发类型转换错误。 - 关联数组未取具体值:预处理代码中
$round = $result6->fetch_assoc();返回的是数组(如['Round' => 2]),直接绑定数组会触发“数组转字符串”警告。 - 循环范围错误:
foreach($_POST as $bid => $value)会遍历所有POST数据(包括按钮、隐藏域),导致无效插入。
修复步骤
- 提取查询结果的具体字段:从
fetch_assoc()返回的数组中取出对应字段值,比如$current_round = $round_data['Round'];。 - 关联输入框与对应记录:修改输入框命名为
newbid[{$row['bidtable']}],同时用隐藏域存储对应乐队名称,避免重复查询。 - 精准循环投标数据:直接遍历
$_POST['newbid']数组,跳过空值或无效输入。
修复后完整代码示例
表格部分修改
<form action="" method="POST"> <table class="table table-hover"> <thead class="thead"> <tr class="header"> <th>ID</th> <th>Band</th> <th>Current Price</th> <th>New Bid</th> </tr> </thead> <tbody> <?php $sql = "SELECT * FROM BidTables WHERE ItemID = ? ORDER BY `Round` DESC"; $stmt = $db->prepare($sql); $stmt->bind_param("i", $_GET['ItemId']); $stmt->execute(); $resultSQL = $stmt->get_result(); while($row = $resultSQL->fetch_assoc()) { ?> <tr> <td><?=$row['bidtable']?></td> <td><?=$row['BandName']?></td> <td><?=$row['BidPrice']?></td> <td><input type="number" name="newbid[<?=$row['bidtable']?>]" size="10" /></td> <input type="hidden" name="bandname[<?=$row['bidtable']?>]" value="<?=$row['BandName']?>" /> </tr> <?php } ?> </tbody> </table> <button class="btn btn-primary btn-lg" name="save">Submit</button> </form>
提交处理部分修改
<?php if (isset($_POST['save']) && !empty($_POST['newbid'])) { $biduserID = $_SESSION['id']; $itemID = $_GET['ItemId']; // 获取当前轮次 $sql6 = "SELECT `Round` FROM `RoundCounter` WHERE `ItemID` =?"; $stmt6 = $db->prepare($sql6); $stmt6->bind_param("i", $itemID); $stmt6->execute(); $result6 = $stmt6->get_result(); $round_data = $result6->fetch_assoc(); $current_round = $round_data['Round']; // 获取当前用户名 $sql7 = "SELECT `Username` FROM `User` WHERE `UserID` = ?"; $stmt7 = $db->prepare($sql7); $stmt7->bind_param("i", $biduserID); $stmt7->execute(); $result7 = $stmt7->get_result(); $user_data = $result7->fetch_assoc(); $username = $user_data['Username']; // 循环处理每个投标 foreach($_POST['newbid'] as $bid_table_id => $bid_price) { if(empty($bid_price) || !is_numeric($bid_price)) continue; $band_name = $_POST['bandname'][$bid_table_id]; $sql4 = "INSERT INTO BidTables (`BandName`,`BidderID`, `ItemID`, `BidPrice`, `Round`, `Username`) VALUES (?,?,?,?,?,?)"; $stmt = $db->prepare($sql4); if(!$stmt) { echo $db->error; continue; } $stmt->bind_param("siiiis", $band_name, $biduserID, $itemID, $bid_price, $current_round, $username); $stmt->execute(); } echo "投标提交成功"; } ?>
额外优化建议
- 输入验证:添加投标价格必须大于当前价格、为正数的逻辑。
- 事务处理:批量插入时使用事务,确保数据一致性。
- 会话校验:验证
$_SESSION['id']有效性,防止未登录提交。
内容的提问来源于stack exchange,提问作者Avzi
相关产品推荐
相关产品推荐

