php单击实现“添加”按钮增加一行单项,并将所有内容插入数据库中
时间: 2024-03-12 09:49:36 浏览: 19
首先,你需要在页面中添加一个“添加”按钮,并且绑定一个点击事件。在点击事件中,你需要使用 JavaScript 动态添加一行单项,并且将新添加的单项的内容保存在一个对象中。
在保存完所有单项的内容后,你可以使用 Ajax 将数据发送到后台 PHP 文件中,然后在 PHP 文件中将数据插入到数据库中。
以下是一个简单的示例代码:
HTML 代码:
```html
<table id="items">
<thead>
<tr>
<th>名称</th>
<th>数量</th>
<th>价格</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="name[]" /></td>
<td><input type="number" name="quantity[]" /></td>
<td><input type="number" name="price[]" /></td>
</tr>
</tbody>
</table>
<button id="add-item">添加</button>
<button id="submit-items">提交</button>
```
JavaScript 代码:
```javascript
// 添加一个新的单项
function addItem() {
const table = document.querySelector('#items tbody');
const row = document.createElement('tr');
row.innerHTML = `
<td><input type="text" name="name[]" /></td>
<td><input type="number" name="quantity[]" /></td>
<td><input type="number" name="price[]" /></td>
`;
table.appendChild(row);
}
// 提交所有单项到后台 PHP 文件中
function submitItems() {
const items = [];
const rows = document.querySelectorAll('#items tbody tr');
rows.forEach((row) => {
const name = row.querySelector('input[name="name[]"]').value;
const quantity = row.querySelector('input[name="quantity[]"]').value;
const price = row.querySelector('input[name="price[]"]').value;
items.push({ name, quantity, price });
});
// 发送 Ajax 请求
const xhr = new XMLHttpRequest();
xhr.open('POST', 'insert.php');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send(JSON.stringify(items));
}
// 绑定点击事件
const addItemBtn = document.querySelector('#add-item');
addItemBtn.addEventListener('click', addItem);
const submitItemsBtn = document.querySelector('#submit-items');
submitItemsBtn.addEventListener('click', submitItems);
```
PHP 代码:
```php
<?php
// 获取 POST 请求中的数据
$data = json_decode(file_get_contents('php://input'), true);
// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 将数据插入到数据库中
foreach ($data as $item) {
$name = $item['name'];
$quantity = $item['quantity'];
$price = $item['price'];
$sql = "INSERT INTO items (name, quantity, price) VALUES ('$name', '$quantity', '$price')";
$conn->query($sql);
}
// 关闭连接
$conn->close();
echo '数据已保存到数据库中!';
```
请注意,这只是一个简单的示例,实际上你需要根据自己的业务需求编写更完善的代码。同时,为了安全起见,你应该对用户输入的数据进行验证和过滤。