使用MySQLi从HTML表单向数据库插入多行 [英] Insert multiple rows to database from HTML form using MySQLi

查看:83
本文介绍了使用MySQLi从HTML表单向数据库插入多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个使用数组的表单,因此一旦提交并处理了多行,就将其插入数据库.我的主程序比下面的要复杂,但是我无法使其正常工作,因此我决定创建一个小的简单程序以更好地理解基本语法,然后将技术应用于主程序.我已经使用过时的MySQL使它正常工作,但是将其转换为MySQLi会引起一些问题,我想知道是否可以得到帮助.

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.

我的表单是这样设置的

<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>

和使用MySQLi更新数据库的php页面如下

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();
}
?>

推荐答案

或者,以较少的代码重写现有代码:

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();

这篇关于使用MySQLi从HTML表单向数据库插入多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆