handling duplicate records in mysql Insert statement

前端 未结 4 1931
被撕碎了的回忆
被撕碎了的回忆 2021-01-26 10:59

Im i have a php form to enter data into a mysql database, my question is how do i handle duplicate records for example if an ID number already exsists how do i check if exsists

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-26 11:52

    As long as there is a suitable UNIQUE KEY or PRIMARY KEY on the field that needs to be unique you will receive an error when you try to insert the duplicate record. You can then test for this error in your code.

    $values = $_POST;
    foreach ($values as &$value) {
        $value = mysql_real_escape_string($value);
    }
    
    $sql1="INSERT INTO loan (loan_id) VALUES ('$values[loan_id]')";
    
    $result = mysql_query($sql1);
    if (!$result) {
        if (mysql_errno() == 1586) {
            echo "ID is already in the database";
        } else {
            die('Invalid query: ' . mysql_error());
        }
    }
    

提交回复
热议问题