douyi1084 2014-11-21 14:50
浏览 80
已采纳

使用MySQLi从HTML表单向数据库插入多行

I'm trying to make a form that uses arrays so once it is submitted and processed multiple rows get inserted into my database. My main program is more complex than below but I could not get it working so I decides to create a small simple program to understand the basic syntax better then apply the techniques to the main program. I have got it to work using the depreciated MySQL but converting it to MySQLi is causing problems that I wonder if I can get help with.

My form is set up like this

<html>
<title>multi row insert test form</title>
<body>
<table>
<form action="process2.php" method="post">
<tr>
<th>forename</th>
<th>surname</th>
<th>level</th>
</tr>
<tr>
<td><input type="text" name="fname[]"></td>
<td><input type="text" name="sname[]"></td>
<td> 
<select name="level[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select> 
</td>
</tr>
<tr>
<td><input type="text" name="fname[]"></td>
<td><input type="text" name="sname[]"></td>
<td> 
<select name="level[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select> 
</td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
</form>
</table>
</body>
</html>

and the php page that updates the database using MySQLi is as below

<?php
include 'dbconnect2.php';
$fname = $_POST['fname'];
$sname = $_POST['sname'];
$level = $_POST['level'];


if ($stmt = $mysqli->prepare("INSERT INTO people (fname, sname, level) values (?, ?, ?)")) {

$stmt->bind_param('ssi', $fname, $sname, $level);

for ($i=0; $i<2; $i++)
{
$fname[$i] = $fname;
$sname[$i] = $sname;
$level[$i] = $level;

$stmt->execute();
echo "Done";
}

$stmt->close();
}
?>
  • 写回答

2条回答 默认 最新

  • dtwr2012 2014-11-21 15:02
    关注

    Or, with less rewriting your existing code:

    $fnames = $_POST['fname'];
    $snames = $_POST['sname'];
    $levels = $_POST['level'];
    
    $stmt = $mysqli->prepare("INSERT INTO people (fname, sname, level) values (?, ?, ?)")
    
    for ($i=0; $i<count($fnames); $i++) {
        $fname = $fnames[$i];
        $sname = $snames[$i];
        $level = $levels[$i];
        $stmt->bind_param('ssi', $fname, $sname, $level);
    
        $stmt->execute();
    }
    echo "Done";
    
    $stmt->close();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘