I would like to know if it is possible to get the column name that made the duplicate error on an INSERT ?
For example, with an unique key on username and another unique key on email :
try{
$pdo->query("INSERT INTO `table`(`username`,`email`)`VALUES('Superman','xxx#xx.com')");
} catch (PDOException $e) {
if($e->errorInfo[0] == '23000' && $e->errorInfo[1] == '1062'){
throw new CustomException("Bla bla already exists");
// How does we get the duplicated column and then display "Email already exists" or "Username already exist"
} else {
throw $e;
}
}
How does we get the duplicated column info and then display "Email already exists" or "Username already exist" instead of "Duplicate entry (ok but which one?)
Thank you,
You can check value in db or grab colum name in the error message for your users.
try{
$pdo->query("INSERT INTO `table`(`username`,`email`) VALUES ('Superman','xxx#xx.com')");
} catch (PDOException $e) {
if (preg_match("/Duplicate entry .+ for key '(.+)'/", $e->getMessage(), $matches)) {
throw new CustomException($matches[1]." already exist");
} else {
throw $e;
}
}
also maybe you prefer to use exec command for "non result query string".
$affectedRow = $pdo->exec("INSERT INTO `table`(`username`,`email`) VALUES ('Superman','xxx#xx.com')");
Thanks for the idea. Didnt think that error could give me this info.
So it will result as this :
try {
$query = $this->dbh->prepare('INSERT INTO users (username,email) VALUES ("test", "test")');
$result = $query->execute();
} catch (PDOException $e) {
if( $e->errorInfo[0] == '23000' && $e->errorInfo[1] == '1062' ){
if( strpos($e->getMessage(), 'username') == true ) $result = 'duplicate_username';
elseif( strpos($e->getMessage(), 'email') == true ) $result = 'duplicate_email';
} else {
throw $e;
$return = false;
}
}
Basically doing the job.
Thanks,
Related
I have a vote.php file that contains the following function.
switch ($ussdRequest->Message) {
case '1':
$db = new DB();
// save_vote will check to see if the person has already voted
$phone_number = $ussdRequest->Mobile;
//Return the array number for the selected vote to be used when updated votes
$items2 = array('1' => 'Origin Beer', '2' => 'Club Beer', '3' => 'Star Beer', '4' => 'Guinness', '5' => 'Gulder');
$voted_for = array_search($ussdRequest->ClientState, $items2) ;
$response = $db->save_vote($phone_number, $voted_for);
//echo $response;
//Display Success message after vote saved.
$ussdResponse->Message =
'Thank you. You have successfully voted for '
. $ussdRequest->ClientState . ' as your preferred Product of the Year.';
break;
case '2':
$ussdResponse->Message = 'Vote cancelled.';
break;
default:
$ussdResponse->Message = 'Invalid selection';
break;
}
$ussdResponse->Type = "Release";
break;
And a db.php file that contains the following function that is executed in the vote.php file above.
function save_vote($phone_number, $voted_for) {
// Just the digits, please
$phone_number = intval(preg_replace('/\D/', '', $phone_number));
// Check to see if person has already voted
//$stmt = $this->db->prepare("SELECT COUNT(*) FROM voters WHERE phone_number=?");
//$stmt->bindValue(1, $phone_number, PDO::PARAM_INT);
//$stmt->execute();
//Try catch exception to check connection to Database.
try{
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected !";
//Check to see if person has already voted
try{
$stmt = "SELECT COUNT(*) FROM voters WHERE phone_number=?";
$results = $this->db->prepare($stmt);
$results->bindParam(1, $phone_number, PDO::PARAM_INT);
//Verify execution of query
if($results->execute()){
// If number not already voted, save their vote
if ($results->fetchColumn() == 0)
{
// Save voter
$stmt2 = "INSERT INTO voters (phone_number, voted_for) VALUES (?, ?)";
$stmt2query = $this->db->prepare($stmt2);
$stmt2query->bindValue(1, $phone_number, PDO::PARAM_INT);
$stmt2query->bindValue(2, $voted_for, PDO::PARAM_INT);
$stmt2query->execute();
// Update vote count
$stmt3 = "UPDATE brands SET votes = votes + 1 WHERE id=?";
$stmt3query = $this->db->prepare($stmt3);
$stmt3query->bindValue(1,$voted_for, PDO::PARAM_INT);
$stmt3query->execute();
return true;
//'Thank you, your vote has been recorded';
}
else {
return false; //'Sorry, you can only vote once.';
}
}
else {
return "There is some problem in updating your profile. Please contact site admin";
}
}
catch (PDOException $e) {
echo $e;
die();
}
//$values = $results->fetchAll(PDO::FETCH_OBJ);
//echo $values;
}
catch (PDOException $e) {
echo $e;
die();
}
}
I wish to know how to return a boolean value to help determine the success or error message from the vote.php file.
that is. If the number casting the vote per the code in the db.php is a repeated number, the save_vote function should return a boolean value so I can check that in the vote.php file and display a message.
I am not sure how to go about returning the boolean value to the vote.php file.
As it stands regardless of the response the code in the vote.php file always execute a thank you message which should not be the case.
what and how can I return a value to the code in the vote.php file to be used to determine the message displayed?
you are already returning True when OK, False when NOK. Just avoid returning a string message in other error cases.
I can see [return "There is some...]. You can instead throw an exception in case of technical error [throw new Exception('There is some...')] and handle exceptions using try/catch when you call save_vote.
to summerize:
Vote OK: return True
Vote NOK: return False
Internal Error: throw an exception
I am trying to get a mysql data from the table, here -
try
{
$stmt = $user->prepare("SELECT status FROM users");
$result=$stmt->fetch(PDO::FETCH_ASSOC);
if($result['status'] != "Y")
{
$error[] = "Some error warning!";
}
else
{
// Some php codes
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Here user is a class where prepare is db connection mysql prepare function. The error always prints - "Array!". I am new to php. Any help will be appreciated.
EDIT: I have managed to solve the problem.
You forgot the call of PDOStatement::execute(). See php.net for some examples.
Have you already tried this?
try
{
$stmt = $user->prepare("SELECT status FROM users");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result['status'] != "Y")
{
$error[] = "Some error warning!";
}
else
{
// Some php codes
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Regarding the Array! output: Did you post the whole code of your script? Were do you try to print the array $error?
I am trying catch database errors within a transaction and if one occurs then rollback and throw an exception.
However, the code is stopping and displaying the db error screen before it throws the exception.
Any ideas how I can make it detect db error without stopping running the subsequent code?
try {
$this->my_function($data);
} catch (Exception $e) {
var_dump($e);
}
private function my_function($data)
{
$this->db->trans_start();
foreach($data as $reg)
{
$sql = $this->db->insert_string('my_table', $reg);
if($this->db->query($sql))
{
continue;
} else {
$this->db->trans_rollback();
throw new Exception('Exception message here...');
}
}
$this->db->trans_complete();
}
This has been answered before on this question
As answered by cwallenpoole:
In application/config/database.php set
// suppress error output to the screen
$db['default']['db_debug'] = FALSE;
In your model or controller:
// try the select.
$dbRet = $this->db->select($table, $dataArray);
// select has had some problem.
if( !$dbRet )
{
$errNo = $this->db->_error_number()
$errMess = $this->db->_error_message();
// Do something with the error message or just show_404();
}
Or in you case:
private function my_function($data)
{
$errors = array();
$this->db->trans_start();
foreach($data as $reg)
{
$sql = $this->db->insert_string('my_table', $reg);
if($this->db->query($sql))
{
continue;
} else {
$errNo = $this->db->_error_number()
$errMess = $this->db->_error_message();
array_push($errors, array($errNo, $errMess));
}
}
$this->db->trans_complete();
// use $errors...
}
Even better
I believe this question has all the answers you need because it takes multiple inserts into account and let's you finish the once that did not return an error.
The email is not being inserted into the database, however I am receiving an echo of success without any errors. I'm not sure what is going wrong. I've tried it with a duplicate email and I get the duplicate email message so it is connecting to the database, and it will not insert when it is a duplicate; however, it seems to not be inserting anything when it is not a duplicate. It seems to just skip the step of uploading.
<?php
include 'db_functions.php';
$_POST['email'] = 'somenewemail#gmail.com';
if(isset($_POST['email']) && ($_POST['email'] != NULL || $_POST['email'] != '')){
$ERRORS = array();
$cleanEmail = htmlentities($_POST['email']);
$database = dbconnlocal();
$queryEmailExists = $database->prepare("SELECT email FROM email_list WHERE email= ?");
$queryUploadEmail = $database->prepare("INSERT INTO email_list (email) VALUES ( ? )");
$database->beginTransaction();
try
{
$queryEmailExists->execute(array($cleanEmail));
$results = $queryEmailExists->fetchAll(PDO::FETCH_ASSOC);
$dbEmail = $results[0]['email'];
if(trim($dbEmail) == trim($cleanEmail)) {
// duplicate email
throw new Exception('duplicateEmail');
} else {
// new email
$queryUploadEmail->execute(array($cleanEmail));
echo json_encode('success');
}
}
catch (Exception $e)
{
switch(trim($e->getMessage())) {
case 'duplicateEmail':
// handle duplicate error
$ERRORS['error'] = 'duplicateEmail';
break;
default:
// handle default errors
$ERRORS['error'] = 'default';
break;
}
echo json_encode($ERRORS['error']);
}
} else { echo json_encode('emptyEmail'); /* empty email */ };
?>
I M Using YII to develop web application
i want to check if query executed successfully or not
$data = Yii::app()->db->createCommand($SQL);
$result = $data->queryAll();
if(count($result) == 0)
{
throw new SoapFault('Sender', 'Unable to get display information.');
}
if code will execute if select query return no result-set. but i want to check if query executed successfully or not. based on that i want to throw exception. then if query executed successfully and returned no result-set then some other exception.
how to do this ? any suggestions ?
try {
$result = $data->queryAll();
} catch (Exception $ex) {
echo 'Query failed', $ex->getMessage();
}
try
{
$result = Yii::app()->db->createCommand($sqlQuery)->execute();
echo 'success';
}
catch (Exception $e)
{
echo 'fail';
}