如果数据存在,则从数据库中删除数据

时间:2016-12-12 06:48:07

标签: php html

我想从数据库中删除数据,如果数据库中存在相同的数据,但我的编码不起作用。如果用户输入数据不匹配,则应显示错误警告。

HTML

<form action="" method="POST">
<input type="number" name="student_id_delete" placeholder="Enter Student ID"/>   
<input type="submit" name="sub_delete" value="Delete"/>
</form>

PHP

define('HOST','localhost');
define('USER','root');
define('PASSWORD_HOST','');
define('DATABASE','ubhs');

if(defined('HOST') && defined('USER') && defined('PASSWORD_HOST') && defined('DATABASE')){
$conn = mysqli_connect(HOST, USER, PASSWORD_HOST, DATABASE);
}else{
die(connection_failed.mysqli_connection_error());
}

$userinput = true;
$student_id_delete = $_POST['student_id_delete'];

if(isset($_POST['sub_delete'])){
  if(empty($student_id_delete)){
     $userErr1 = "Please enter student ID to be deleted";
     $userinput = false;
  }
  $sql = "SELECT FROM student_info WHERE id=$student_id_delete";
  $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result)<0){
    echo "student could not be found in database";
    $userinput = false;
    }
if($userinput==true){
       $sql = "DELETE FROM student_info WHERE id=$student_id_delete";
        if(mysqli_query($conn,$sql)){
        echo "Success";
        }else{
         echo "Couldn't deleted";
        }
  }
}

1 个答案:

答案 0 :(得分:1)

尝试以下代码段:

HTML code:

<form action="" method="POST">
    <input type="number" name="student_id_delete" placeholder="Enter Student ID"/>   
    <input type="submit" name="sub_delete" value="Delete"/>
</form>

PHP代码:

<?php

    define('HOST','localhost');
    define('USER','root');
    define('PASSWORD_HOST','');
    define('DATABASE','ubhs');

   if(defined('HOST') && defined('USER') && defined('PASSWORD_HOST') && defined('DATABASE'))
   {
        $conn = mysqli_connect(HOST, USER, PASSWORD_HOST, DATABASE);
   }
   else
   {
       die(connection_failed.mysqli_connection_error());
   }

   $userinput = true;
   $student_id_delete = $_POST['student_id_delete'];

   if(isset($_POST['sub_delete']))
   {
       if(empty($student_id_delete))
       {
        $userErr1 = "Please enter student ID to be deleted";
        $userinput = false;
       }

       if($userinput==true)
       {
            $sql = "DELETE FROM student_info WHERE id=".mysqli_real_escape_string($student_id_delete); // sql injection prevention.
            mysqli_query($conn,$sql);
            echo "Records deleted: ".mysqli_affected_rows($conn);
       }
   }
?>

输出: 删除的记录:1 删除的记录:0