我当前以表格格式显示表product中的所有信息,我有一个按钮ADD,单击该按钮时应该仅将表product中的id、名称和价格添加到同一数据库中的表product_add中。但我的问题是,当我单击“ADD”按钮时,product_add 表中没有输入任何内容。
<?php
include'connect.php';
$image =$_GET['image'];
$id =$_GET['id'];
$name =$_GET['name'];
$price=$_GET['price'];
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0)
{
?>
<form method="post" id="form" name="form">
<table border='1'>
<?php
while ($row = mysql_fetch_array($result))
{
extract($row);
?>
<tr>
<td><?php echo $row['id']?></td>
<td><img src=<?php echo $row['image'] ?> /></td>
<td><?php echo $row['name']?></td>
<td><?php echo $row['price']?></td>
<td><input type='button' value='ADD' id="insert" name="insert"/></td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if(isset($_REQUEST['insert']))
{
$insert = "INSERT INTO product_add(id, name, price)
VALUES ('$row[id]','$row['name']','$row['price']')";
$insertQuery=mysql_query($insert);
}
?>
</body>
</html>
我已经更新了代码,如下所示,但表product中的最后一行被添加到表product_add中。当我单击“提交”按钮时,我只想添加特定行。
<?php
include'connect.php';
$image = isset($_GET['image']) ? $_GET['image'] : "";
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price= isset($_GET['price']) ? $_GET['price'] : "";
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0){
?>
<form method="POST" id="form" name="form">
<table border='1'>
<tr>
<th>Id</th>
<th>Image</th>
<th>Name</th>
<th>Price MUR</th>
</tr>
<?php
while ($row = mysql_fetch_array($result)){
extract($row);
?>
<tr>
<td><input name="id" value="<?php echo htmlspecialchars($row['id']); ?>">
</td>
<td><img src=<?php echo $row['image'] ?> width='120' height='100'/></td>
<td><input name="name" value="<?php echo htmlspecialchars($row['name']);
?>"></td>
<td><input name="price" value="<?php echo htmlspecialchars($row['price']);
?>"></td>
<td>
<input id="submit" type="submit" name="submit" value='Add to cart' />
</td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if (isset($_REQUEST['submit']))
{
$insert = "INSERT INTO product_add(id, name, price) VALUES ('$id',
'$name','$price')";
$insertQuery=mysql_query($insert);
}
?>
最佳答案
除了方法(如果您的表单使用POST,您应该在php中使用$_POST
)之外,您没有任何表单字段。
例如:
<?php echo $row['id']?>
应该是这样的:
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
和:
<?php echo $row['name']?>
应该是:
<input name="name" value="<?php echo htmlspecialchars($row['name']); ?>">
等等
您还应该切换到 PDO 或 mysqli 和准备好的语句,因为您现在的代码很容易受到 SQL 注入(inject)的攻击。并且html中的ID需要是唯一的。
关于php - 单击按钮时插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23763553/