I am trying to create a php script to add new users. The username is unique, so if a new users tries to use a name already used the SQL fails. I am trying to catch the error using the following code:
<?php
include 'dbConn.php';
if (!isset($_SESSION['username'])) session_start();
$username = 'foo';
$userpass = 'foopass';
$userrole = 1;
global $mysqli;
try{
connect();
$mysqli -> autocommit(FALSE);
$sqluser= "INSERT INTO users (login,password,role_id) VALUES(?,?,?); ";
$stmt = $mysqli->prepare($sqluser);
$stmt->bind_param("ssi", $username, $userpass , $userrole);
$res = $stmt->execute(); //Fatal error: Uncaught mysqli_sql_exception: Duplicate entry
if($res){
$mysqli->commit();
$mysqli->autocommit(TRUE);
echo "<p>New Account created!</p>";
}else{
$mysqli->rollback();
$mysqli -> autocommit(TRUE);
echo "<p>New Account creation Failed - Maybe the username already exists!";
}
}catch(err){
$mysqli->rollback();
$mysqli -> autocommit(TRUE);
echo "<p>New Account creation Failed - Maybe the username already exists!";
}
?>
However the code breaks in line $res = $stmt->execute();
showing a Fatal error message.
How should I catch the SQL error from PHP?