Reputation: 45
I create simple a Registration Form that connect with mysql
html code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form method="post" enctype="multipart/form-data>">
<div class="form-group">
<label for="username"> User Name</label>
<input type="text" name="username" id="username">
</div>
<br>
<div class="form-group">
<label for="password"> password</label>
<input type="password" name="password" id="password">
</div>
<br>
<div class="form-group">
<label for="age"> Age</label>
<input type="text" name="age" id="age">
</div>
<br>
<button class="btn btn-primary btn-block" name="b_send"> send data</button>
</form>
</div>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.js"></script>
</body>
</html>
mysql : dbname is = final table is = students
in table students i have column (username) and i set it to UNIQUE ,
in php code i make connection :
<?php
if ($_SERVER['REQUEST_METHOD']=="POST"){
if(isset($_POST['b_send'])){
$username= $_POST['username'];
$password=$_POST['password'] ;
$age=$_POST['age'];
try{
$conn=new PDO ("mysql:host=localhost; dbname=final",
"admin","admin");
$sendvalues=$conn->exec("insert into students(username,password,age)
values('$username','$password','$age')");
}
catch(PDOExeption $e){
echo "error in data send";
}
}
}
?>
now , i want to make check , if user has enter duplicate name that already exist in column (username), it prevent sending data to db and give user error message
thanks in advance
Upvotes: 0
Views: 288
Reputation: 1509
Either your keep using insert into
and catch an error if one occured while executing the query like this:
try {
$conn->exec("insert into students(username,password,age)
values('$username','$password','$age')");
// do other things if successfully inserted
} catch (PDOException $e) {
if ($e->errorInfo[1] == 1062) {
// duplicate entry, do something else
} else {
// an error other than duplicate entry occurred
}
}
Because you set the column username
to UNIQUE
the execution will throw an error when trying to insert a duplicate entry.
or you can use insert ignore
and completely ignore an error message.
read more about insert ignore
here
Upvotes: -2