錯誤代碼,我想從數據庫中添加員工與屬性ID和empName記錄表 '池'如何捕捉在PHP
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 = mysql_query($tableSQL);
if($result){
print "success!";
}
else{
print "fail!";
}
}
mysql_close($db_handle); //close the connection;
?>
在數據庫中,ID是唯一的,也是INT數據類型,我想捕獲用戶輸入數據庫中已存在的ID值的錯誤代碼。我們如何做到這一點?
首先,您應該防止發生任何錯誤,例如:通過[保護您的腳本免受SQL注入](http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php)。然後你應該[查看mysql函數的手冊](http://www.php.net/manual/en/function.mysql-errno.php)。 – hakre
什麼是'$ id'?爲什麼用戶指定它? – zerkms
您可以使用['mysql_error'](http://www.php.net/manual/en/function.mysql-error.php)檢索錯誤消息,以避免出現'$ result === false'的情況。請注意,您的數據庫代碼非常不安全並且允許SQL注入。 –