Nibesh Khadka Nibesh Khadka - 6 months ago 14
SQL Question

Error Creating record in MySQL: "Integrity constraint violation"

I am trying to create a registration file and I used this code for creating it:

<?php
require 'connection.php';

if (isset($_POST['submit'])) {
$res= $conn->prepare("Insert into user (Name,Email,user_name,password)Values (:name,:email,:user,md5(:pass))");
$res->bindParam(':name', $name);
$res->bindParam(':email', $email);
$res->bindParam(':user', $user);
$res->bindParam(':pass', $pass);

$name = $_POST['name'];
$email = $_POST['email'];
$username =$_POST['user'];
$password = $_POST['pass'];

$res->execute();

if ($res==TRUE) {
echo 'Registered successfully';
} else {
echo 'There was some error.';
}
}
?>


But I get this error:


Integrity constraint violation: 1048 Column 'user_name' cannot be
null'


Here is the HTML part of my code.

<body>
<form action="Registration.php" method="post" >
Name:<br>
<input type="text" name="name"/><br>
Email:<br>
<input type="text" name="email" /><br>
Username:<br>
<input type="text" name="user" /><br>
Password:<br>
<input type="password" name="pass" /><br>
<input type="submit" name="submit" value="SignUp!"/>
</form>
</body>

Answer

Mark Baker's comment is correct and highlights the core problem. You are binding the username to a variable $username, but your SQL statement is looking for $user. Because the $user variable is not set, it is null and violates your database constraints when the SQL statement is executed.

Adjust your code to

$user =$_POST['user'];

and it should work

Comments