我想更改错误代码SQLSTATE [23000]:完整性约束违规:1062重复条目' xx@yahoo.com'关键词'电子邮件'消息变成类似"错误电子邮件已在使用"
create.php
<?php
require_once 'dbconfig.php';
if ($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$contactnum = $_POST['contactnum'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$lang = $_POST['lang'];
try {
$stmt = $db_con->prepare("INSERT INTO tbluser(fname,lname,contactnum,email,pass,lang) VALUES(:ufname,:ulname,:ucontact,:uemail,:upass,:ulang)");
$stmt->bindParam(":ufname", $fname);
$stmt->bindParam(":ulname", $lname);
$stmt->bindParam(":ucontact", $contactnum);
$stmt->bindParam(":uemail", $email);
$stmt->bindParam(":upass", $pass);
$stmt->bindParam(":ulang", $lang);
if ($stmt->execute()) {
echo "Successfully Added";
} else {
echo "Query Problem";
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
我尝试添加类似这样的内容
if (mysql_errno() == 1062) {
echo"error email already in use!";
}
但无法使其发挥作用。谢谢你的帮助,我还是php的新手。有人可以告诉我如何使用PDO吗?
addform.php
<style type="text/css">
#dis{
display:none;
}
</style>
<div id="dis">
<!-- here message will be displayed -->
</div>
<form method='post' id='emp-SaveForm' action="#">
<table class='table table-bordered'>
<tr>
<td>First Name</td>
<td><input type='text' name='fname' class='form-control' required /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type='text' name='lname' class='form-control' required></td>
</tr>
<tr>
<td>Contact Number</td>
<td><input type='number' name='contactnum' class='form-control' required></td>
</tr>
<tr>
<td>Email</td>
<td><input type='email' name='email' class='form-control' required /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name='pass' class='form-control' required /></td>
</tr>
<tr>
<td>Language</td>
<td><input type='text' name='lang' class='form-control' required /></td>
</tr>
<tr>
<td colspan="2">
<button type="submit" class="btn btn-primary" name="btn-save" id="btn-save">
<span class="glyphicon glyphicon-plus"></span> Save this User
</button>
</td>
</tr>
</table>
</form>
答案 0 :(得分:2)
mysql_errno
是已弃用的mysql扩展的一部分 - 您正在使用PDO,因此您还需要使用它来检查错误:
if ($stmt->execute()) {
echo "Successfully Added";
} else {
if ($stmt->errorCode() == 1062) {
# Here ^
echo "error email already in use!";
} else {
echo "some other problem...";
}
}
答案 1 :(得分:1)
错误可能会出现在事件/错误日志中,并且如果您试图找到合法错误会导致不必要的噪音,所以如果可以,我会避免依赖它们。而是尝试:
IF (SELECT 1 = 1 FROM users WHERE email=?) THEN
BEGIN
SELECT 0 AS Result--signals already exists to the application
END;
ELSE
BEGIN
INSERT INTO users(columns) VALUES(values);
SELECT LAST_INSERT_ID() AS Result;
END;
END IF;
或者那些东西。