MySQL只用while循环插入最后一行
我有一个while循环。它在一个表单中。我想在提交提交按钮时插入while循环中的所有行。以下是while循环的代码。MySQL只用while循环插入最后一行
<form method="POST" action="insert.php" n>
<table>
<?php
$i =0;
$link = mysqli_connect('localhost', 'root', '', 'shibu');
$sql = "select `cus_id`, `mobile`, `date`, `time`,
sum(`d1` + `d2` + `d3`) as `credit`,
from `finale`;
$result=mysqli_query($link, $sql);
$count = mysqli_num_rows($result);
if($count == 0){
?>
<tr>
<th><?php echo 'No Records Founds!' .mysqli_error($link); ?></th>
</tr>
<?php
}else{
while($sql_result = mysqli_fetch_assoc($result)){
?>
<tr>
<td><?php echo $i += 1; ?></td>
<td><input type="text" name="cus_id" value="<?php echo $sql_result['cus_id']; ?>" ></td>
<td><input type="text" name="mobile" value="<?php echo $sql_result['mobile']; ?>" ></td>
<td><input type="text" name="date" value="<?php echo $sql_result['date']; ?>" ></td>
<td><input type="text" name="time" value="<?php echo $sql_result['time']; ?>"</td>
<td><input type="text" name="credit" value="<?php echo $sql_result['credit']; ?>"></td>
</tr>
<?php
}
}
?>
</table>
<input name="submit" type="submit" />
</form>
这是我的插入查询。
<?php
$link = mysqli_connect('localhost', 'root', '', 'shibu');
$stmt = mysqli_prepare($link, "INSERT INTO single
(`cus_id`, `mobile`, `date`, `time`, `credit`) VALUES (?,?,?,?,?)");
mysqli_stmt_bind_param($stmt, 'isssi', $cus_id, $mobile, $date, $time, $credit);
foreach ((array)$_POST['cus_id'] as $i => $cus_id) {
$mobile = $_POST['mobile'];
$date = $_POST['date'];
$time = $_POST['time'];
$credit = $_POST['credit'];
mysqli_stmt_execute($stmt);
}
if(!$stmt){
echo "error". mysqli_error($link);
}
我的问题是,当我进入submit
按钮,only last row enters
不完整行。
我需要你的帮助,衷心。
在您的html代码中,您需要将输入名称定义为数组。
像
<td><input type="text" name="cus_id[]" value="<?php echo $sql_result['cus_id']; ?>" ></td>
<td><input type="text" name="mobile[]" value="<?php echo $sql_result['mobile']; ?>" ></td>
<td><input type="text" name="date[]" value="<?php echo $sql_result['date']; ?>" ></td>
<td><input type="text" name="time[]" value="<?php echo $sql_result['time']; ?>"</td>
<td><input type="text" name="credit[]" value="<?php echo $sql_result['credit']; ?>"></td>
虽然在PHP中使用它们,你需要循环他们和运行插入查询
foreach ($_POST['cus_id'] as $i => $value) {
$cus_id = $_POST['cus_id'][$i];
$mobile = $_POST['mobile'][$i];
$date = $_POST['date'][$i];
$time = $_POST['time'][$i];
$credit = $_POST['credit'][$i];
// Yourinsert query
}
请移动你的
mysqli_stmt_bind_param
行成foreach循环,略高于
mysqli_stmt_execute
线。
mysqli_stmt_bind_param分配的参考。没有必要把它放在循环中。 – IncredibleHat
Randall,请检查$ mobile在代码中的初始化位置。它是在bind_param之后。这就是我上面提出的原因。 – paulz
将值赋给与bind_param绑定的变量,是完全可以接受的mysqli预处理语句。它实际上甚至在PHP手册页hehe显示了这种方式:D http://php.net/manual/en/mysqli-stmt.bind-param.php – IncredibleHat
很好的答案。它根本不是mysql操作,它是如何处理表单中的变量的。 – IncredibleHat
我已更改名称字段。现在,除了'cus_id'字段,'mobile,date和time'字段在单词中显示'array'并且信用字段在数据库中显示'1'。 –
您可以使用print_r($ _ POST)显示$ _POST数据; –