問題描述
當我想在一個表中插入多個字段時遇到問題.
I have a problem when I want to insert multiple fields into one table.
這是我的表格:
<h1>Add user</h1>
<form method="post" action="index.php">
<table>
<thead>
<th>Name</th>
<th>Age</th>
</thead>
<tr>
<td><input name="name[]" type="text" /></td>
<td><input name="age[]" type="text" /></td>
</tr>
<tr>
<td><input name="name[]" type="text" /></td>
<td><input name="age[]" type="text" /></td>
</tr>
<tr>
<td><input name="name[]" type="text" /></td>
<td><input name="age[]" type="text" /></td>
</tr>
</table>
<input type="submit" name="submit" value="Submit" />
</form>
這是提交代碼:
if (isset($_POST['submit'])) {
foreach ($_POST as $val) {
$name = $val['name'];
$age = $val['age'];
mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
}
}
查詢插入到數據庫中,但不是我輸入的值.
The query inserts into the database, but not the values that I've entered.
有人可以幫我嗎?
推薦答案
您正在對 $_POST
而不是 name/age 數組執行 foreach.您應該像這樣對 name 或 age 數組執行 foreach:
You are doing a foreach on $_POST
rather than on the name/age arrays. You should be doing foreach on name or age array like this:
if (
!empty($_POST['name']) && !empty($_POST['age']) &&
is_array($_POST['name']) && is_array($_POST['age']) &&
count($_POST['name']) === count($_POST['age'])
) {
$name_array = $_POST['name'];
$age_array = $_POST['age'];
for ($i = 0; $i < count($name_array); $i++) {
$name = mysql_real_escape_string($name_array[$i]);
$age = mysql_real_escape_string($age_array[$i]);
mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
}
}
我還注意到您目前很容易受到 SQL 注入的影響,因此我添加了為名稱/年齡轉義字符串的步驟.
I would also note that you are currently susceptible to SQL injection so I added the step of escaping your strings for name/age.
我還強烈建議簡單地將單個批量插入到數據庫中,而不是單獨插入每條記錄(我將把它留給您來實現).從性能的角度來看,這種方法幾乎總是更可取的.
I would also highly suggest simply making a single bulk insert into the DB instead of an insert of each record individually (I will leave that up to you to implement). This approach is almost always preferable from a performance standpoint.
最后,您真的不應該使用 mysql_*
函數,因為它們已被棄用.考慮改用mysqli或PDO.
Finally, you REALLY should not be using mysql_*
functions as they are deprecated. Consider changing to mysqli or PDO.
這篇關于使用 foreach 循環插入多個字段的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!