首页 > 解决方案 > preventing duplicate row data entries

问题描述

I had created a database which named student with ID, name, mat_number, specialty, age, and gender, in a PHP application.

I do not want the name or mat_number be taken in more than once.

I have done the connection to my database in a different page and called it in the add student page.

This following codes is for a faculty database collection


    <?php 
                if(isset($_POST['submit']))  {
                    $name = $_POST['name'];
                    $matNo = $_POST['mat_number'];
                    $age = $_POST['age'];
                    $specialty = $_POST['specialty'];
                    $gender = $_POST['gender'];

                    if(!empty($name) && !empty($matNo) && !empty($age) && 
                            !empty($specialty) && !empty($gender))
                {

                    $sql = "INSERT INTO `student`(`name`, `UB_number`, `age`, 
                                          `sex`, `specialty`)
                    VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
                    $conn->query($sql);
                    header("Location: index.php");
                }
                else{
                    echo "Error: Complete all records";
                }          
                }

            ?>

I want to get an error message demanding for a change if the 2 fields already exist in the database.

标签: php

解决方案


如果记录已经存在,则要签入数据库的名字。

如果没有记录运行 sql insert 命令。

 if(isset($_POST['submit']))  {
     $name = $_POST['name'];
     $matNo = $_POST['mat_number'];
     $age = $_POST['age'];
     $specialty = $_POST['specialty'];
     $gender = $_POST['gender'];
        $sql = "SELECT * FROM `student` WHERE name = "'.$name.'" and UB_number = '".$matNo."'";
            $conn->query($sql);
            $cnt = $conn->rowCount();
        if($cnt == 0){
             $sql = "INSERT INTO `student`
                  (`name`, `UB_number`, `age`,`sex`, `specialty`)
                  VALUES
                  ('$name', '$matNo', '$age', '$gender', '$specialty')";
            $conn->query($sql);
            header("Location: index.php");
       }else{
            echo "Error: Complete all records";
       }          
}

推荐阅读