0

I have a register.php file which takes the input from a form and tries to create a user account in a database. I have an innoDB MySQL database which has a 'UNIQUE' key added to the 'username' field of the users table. This is to prevent duplicate usernames.

Below is an extract from my php code. In my database I currently have a user called 'testUser'. However, when running the code below with $username = testUser, the php file returns 'Account created', even though a duplicate row is not created in the database. I would have expected there to be an exception thrown if the user already existed?

try{
    $stmt = $db->prepare("INSERT INTO users (username, password, salt) VALUES (:username,   :password, :salt)");
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':password', $hash);
    $stmt->bindParam(':salt', $salt);
    $stmt->execute();
}catch(PDOException $e){
    returnJSON(0,'Error creating account');
}

returnJSON(1,'Account created');

function returnJSON($errorCode, $message){
    $arr = array("returnCode" => $errorCode, "returnMessage" => $message);
    echo json_encode($arr);
    die();
}

 ----
try{
    $db = new PDO('mysql:host='.$host.';dbname='.$dbname, $username, $password);
}
catch(PDOException $e){
    $arr = array("returnCode" => 0, "returnMessage" => "unable to connect to server");
    echo json_encode($arr);
    die();
}

My question is, how should I find out if the user's account was successfully added to the database.

PS. I do have code to query the database first and see if there exists a user with the same name before calling this code. But I'd still like to fix/understand this as well.

4

2 回答 2

0
catch (PDOException $er) {print("error".$er."<br />");}

When you catch an Error, the flow of the program continues, try catching the Error and stopping the flow, using exit();

What I am saying is , even if an exception is caught, the following line of code should stil execute,

returnJSON(1,'Account created');

unless you are stopping the flow somehow. Would really appreciate if you post the entire file, including functions you are using.

于 2012-09-23T06:43:51.940 回答
0

PDO by default has silent errors: you need to check then yourself by actually looking for them.

If you want to use exceptions, you need to tell PDO to do it. Check http://php.net/manual/en/pdo.error-handling.php

The specific code you want is

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

in the try/catch immediately after you create the connection.

于 2012-09-23T07:25:29.003 回答