PHP:不删除一位数据,但删除两位数据

时间:2014-11-27 14:33:24

标签: php mysql

我有2个PHP页面可以从表中删除员工数据。为此,用户插入员工ID,然后按删除,从表中删除数据。

现在,问题是,每当我插入一位数(2,3,8等)的id时,id都不会被删除。但是,如果插入了两个数字ID(12,19,99等),它将被删除。 请帮我解决我错的地方。

这是我的第一个PHP页面的代码:

<form action="deleteemp.php" method="post" onSubmit="return confirm('Are you sure to delete?')">
  Enter id to delete data<input type="text" name="EmpId" required> 
  <button type="submit" >Delete</button>
</form>

这是我的动作PHP页面,

<?php

$EmpId = $_POST['EmpId'];

$connection = mysql_connect("localhost", "root", "");
if (!$connection) {
    die("Connection failed " . mysql_error());
}
$db_conn = mysql_select_db("hms", $connection);
if (!$db_conn) {
    die("Connection failed " . mysql_error());
}
$query = "DELETE FROM employee_details WHERE emp_id = " . $EmpId;
$db_result = mysql_query($query, $connection);

if ($db_result) {
    echo "Data Deleted Successfully !";
    echo "<br>";
    echo "<a href='homepage.php'>Back to homepage</a>";
} else {
    echo "Data Not there. Try Again !<br>";
    echo "<a href='deleteemp1.php'>Search again</a>";
}

4 个答案:

答案 0 :(得分:2)

echo "data not here"不正确。 mysql_query在FAILURE上返回布尔值false。空结果(没有匹配的ID) NOT 失败。这是一个成功的查询,恰好有一个空的结果集。

您的代码应该更像

$result = mysql_query($query) or die(mysql_error());
if (mysql_affected_rows($result) == 0) { 
   die("No rows deleted");
}

请注意,您很容易受sql injection attacks攻击,并且使用过时/已弃用的数据库库。

答案 1 :(得分:0)

试试这个

$query = "DELETE FROM employee_details WHERE emp_id = '$EmpId'";
$db_result = mysql_query($query, $connection);

if ($db_result)
 {
    echo "Data Deleted Successfully !";
    echo "<br>";
    echo "<a href='homepage.php'>Back to homepage</a>";
} 
else
 {
    echo "Data Not there. Try Again !<br>";
    echo "<a href='deleteemp1.php'>Search again</a>";
}

答案 2 :(得分:0)

这似乎是一个特殊问题,因此在将值传递给SQL查询之前请先尝试typecasting。 尝试使用它为$ EmpId赋值:

$EmpId = (int) $_POST['EmpId'];

答案 3 :(得分:0)

您可以尝试从

更改以下代码

$query = "DELETE FROM employee_details WHERE emp_id = " . $EmpId;

$query = "DELETE FROM employee_details WHERE emp_id =".$EmpId;

试试吧。这可能对你有用