开发者

how to catch error code in PHP

开发者 https://www.devze.com 2023-04-09 23:34 出处:网络
i want to add records to table \'pool\' with attribute ID and empName from database employees theform.html

i want to add records to table 'pool' with attribute ID and empName from database employees

theform.html

<FORM NAME ='form2' METHOD ='POST' ACTION ='result.php' enctype="multipart/form-data">
<B>Board Write</B> <BR>

<INPUT TYPE = Text Name = empID value = 'write ID here'>
<INPUT TYPE = Text Name = empName  VALUE = 'write name here'><P>
<INPUT TYPE = 'Submit' Name = Submit2  VALUE = 'Post'>

</FORM>

result.php

<?PHP

      $ID = $_POST['empID'];
      $NAME = "'" . $_POST['empName'] . "'";

       $server = "127.0.0.1"; //connect to server
       $user_name = "root";   
       $password = "";

       $database = "employees";


    $db_handle = mysql_connect($server, $user_name, $password);
    $db_found = mysql_select_db($database, $db_handle);


if($db_found){// there is a database

$tableSQL = "INSERT INTO pool(ID, empName) VALUES " . "(" . $ID . "," . $NAME . ")";


$result = mysq开发者_C百科l_query($tableSQL);

    if($result){
            print "success!";
    }
    else{
            print "fail!";
        }


}

   mysql_close($db_handle);  //close the connection;



?>

in the database, ID is unique and also an INT datatype, i want to catch the error code where the user inputs an ID value that already existing in the database. how do we do this?


You can use mysql_errno() (or mysqli_errno(), if you use mysqli) to get the error number after a query if it failed (check the return value of mysql_query()). It should be error #1022 (ER_DUP_KEY) according to the mysql error documentation


In general, it is better to prevent SQL errors than to catch them. For example, check whether a duplicate exists before you even try to insert the record.

To avoid the issue altogether, you could use an auto-increment field for the ID, and allow the database to assign new numbers automatically. Then the user would never need to enter it, so there would never be a clash due to duplicates.

If you do still need to check for errors, then you can use the mysql_error() or mysql_errno() functions to get the error details.


    // returns true if duplicated
function duplicate_catch_error ($database_connection) {
    $mysql_error = array (1022 => "Can't write; duplicate key in table '%s'",1062 => "Duplicate entry '%s' for key %d", 1586 => "Duplicate entry '%s' for key '%s'");  // also allows for the use of sscanf
    if (array_key_exists(mysql_error($database_connection),$mysql_error)) // checks if error is in array
        return true;
    else
        return false;
}

hope this answers your question, also mysql is now depreciated. Use mysqli if you didn't already know :)

0

精彩评论

暂无评论...
验证码 换一张
取 消