我有一个问题,我无法解决。当我创建此代码并运行它时,它总是删除mysql数据库的最后一行。请帮助我们.Ty:D
我在发布代码时遇到了一些问题,所以你可以在这里找到它jsfiddle.net/xhCLz/
在“javascript”框下。
<?php
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM test_mysql");
$postid1 ="1";
while($row = mysqli_fetch_array($result))
{
$ime=$row['name'];
$prezime=$row['lastname'];
$id_number=$row['id'];
echo $ime. " " . $prezime. " " .$id_number. "<form action='' method='post'>
<input type='hidden' name='id_number_send' value='<?php echo $id_number?>'/>
<input type='submit' name='send_value' value='delete' />
</form>";
}
if(isset($_POST['send_value']))
{
$delete_row = mysqli_query($con,"DELETE FROM test_mysql WHERE id='$id_number'");
echo $id_number;
}
答案 0 :(得分:1)
你没有从POST中获取id,而是在上一次执行循环时使用id。
您必须从$_POST
变量($_POST['id_number_send']
)获取要删除的行的ID,并在查询中使用它之前清理数据以防止SQL注入({{3} })。
如果要显示没有删除的所有行,也应该在循环之前进行删除。
if(isset($_POST['send_value']))
{
$deleteId = mysqli_real_escape_string($con, $_POST['id_number_send']);
$delete_row = mysqli_query($con,"DELETE FROM test_mysql WHERE id='$deleteId'");
echo "ID number: " . $deleteId . " has been deleted.<br><br>";
}
$result = mysqli_query($con,"SELECT * FROM test_mysql");
$postid1 ="1";
while($row = mysqli_fetch_array($result))
{
$ime=$row['name'];
$prezime=$row['lastname'];
$id_number=$row['id'];
echo $ime. " " . $prezime. " " .$id_number. "<form action='' method='post'>
<input type='hidden' name='id_number_send' value='$id_number' />
<input type='submit' name='send_value' value='delete' />
</form>";
}
答案 1 :(得分:0)
你的while循环最后一次运行时,它会将它找到的最后一个ID分配给变量$ id_number:
while($row = mysqli_fetch_array($result))
{
$ime=$row['name'];
$prezime=$row['lastname'];
$id_number=$row['id'];
//etc.
因此,不应让DELETE查询使用该变量(它始终是它找到的最后一个数字),而应使用提交表单中的变量,即$ _POST变量:
$delete_row = mysqli_query($con,"DELETE FROM test_mysql WHERE id='$_POST['id_number_send']'");