Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6467957
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T05:50:43+00:00 2026-05-25T05:50:43+00:00

Action: creating table record that is a duplicate on a unique key. Good: The

  • 0

Action: creating table record that is a duplicate on a unique key.

Good: The unique key is working because the duplicate record is not created.

Bad: The mysqli functions that I am using in PHP are not failing in the way that I expect.

Meta: I have some PHP (running 5.3.6) that handles creating new records in a Mysql (5.5.9) table from AJAX POST requests. Authentication and input scrubbing and validation is handled outside of the scope of the code that I am sharing. The respond function also handles printing out the response in a valid format. The table I am inserting into has an auto incrementing id column and a unique name column.

// connect to server
$mysqli = new mysqli("localhost", "dbuser", 'dbpassword', "database");
if(mysqli_connect_errno()) {
    $response["message"] = "unable to connect to the MySQL server at 'localhost' as 'dbuser' using a password or select the database 'database' because ".mysqli_connect_errno();
    respond($response);
}

// build and run query
if ($stmt = $mysqli -> prepare("INSERT INTO `database`.`table` (`id`, `name`) VALUES (NULL, ?);")) {
    $stmt -> bind_param("s", $inputs["name"]);
    $success = $stmt -> execute();
    if ($success) {
        $response["status"] = "success";
        $response["id"] = $mysqli -> insert_id;
        respond($response);
    } else {
        $response["message"] = "failed to insert because ".$stmt -> error;
    }

    $stmt -> close();
} else {
    $response["message"] = "unable to build query because ".$mysqli -> error;
    respond($response);
}

$mysqli -> close();

This works as expected when inserting a new unique name but doesn’t return anything when attempting to insert a new duplicate name. I expected the

$stmt -> execute();

to fail so I would return a response explaining the error. This code doesn’t do that. The only way I have found to return that the create failed because of a duplicate is to add 2 lines of code before the close statement like this:

// connect to server
$mysqli = new mysqli("localhost", "dbuser", 'dbpassword', "database");
if(mysqli_connect_errno()) {
    $response["message"] = "unable to connect to the MySQL server at 'localhost' as 'dbuser' using a password or select the database 'database' because ".mysqli_connect_errno();
    respond($response);
}

// build and run query
if ($stmt = $mysqli -> prepare("INSERT INTO `database`.`table` (`id`, `name`) VALUES (NULL, ?);")) {
    $stmt -> bind_param("s", $inputs["name"]);
    $success = $stmt -> execute();
    if ($success) {
        $response["status"] = "success";
        $response["id"] = $mysqli -> insert_id;
        respond($response);
    } else {
        $response["message"] = "failed to insert because ".$stmt -> error;
    }

    $stmt -> close();
} else {
    $response["message"] = "unable to build query because ".$mysqli -> error;
    respond($response);
}

$response["message"] = "Duplicate";
respond($response);

$mysqli -> close();

The thing I don’t understand is when the query runs as expected, the duplicate response is not returned. When the query fails because it is trying to insert a duplicate on the unique key, this returns the duplicate response.

Question: Why does a successful insert not run the respond function at the end of the code block?

Question: Why does a failed insert because of attempting to insert a duplicate on a unique key not throw an exception or fail as I expected?

I have also tried wrapping the entire thing in a try catch block but it didn’t help any because it’s not throwing any exceptions. If you could shed any light on this matter I would greatly appreciate it.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T05:50:43+00:00Added an answer on May 25, 2026 at 5:50 am

    Question: Why does a successful insert not run the respond function at the end of the code block?

    I assume your respond method has an exit or die in it somewhere that halts execution.

    Question: Why does a failed insert because of attempting to insert a duplicate on a unique key not throw an exception or fail as I expected?

    I think it’s to do with the logic in your if statements.

    If your procedure ever gets into the else statement

    $response["message"] = "failed to insert because ".$stmt -> error;
    

    no response is ever sent (the respond function is never called). The reason your second example works is because the code reaches that point every time (because its outside the last else statement. If you move a call to respond after the line above you might find it returns the message as expected. Full code might look like the following:

    // connect to server
    $mysqli = new mysqli("localhost", "dbuser", 'dbpassword', "database");
    if(mysqli_connect_errno()) {
        $response["message"] = "unable to connect to the MySQL server at 'localhost' as 'dbuser' using a password or select the database 'database' because ".mysqli_connect_errno();
        respond($response);
    }
    
    // build and run query
    if ($stmt = $mysqli -> prepare("INSERT INTO `database`.`table` (`id`, `name`) VALUES (NULL, ?);")) {
        $stmt -> bind_param("s", $inputs["name"]);
        $success = $stmt -> execute();
        if ($success) {
            $response["status"] = "success";
            $response["id"] = $mysqli -> insert_id;
            respond($response);
        } else {
            $response["message"] = "failed to insert because ".$stmt -> error;
            respond($response); // <-- this is the bit you need
        }
    
        $stmt -> close();
    } else {
        $response["message"] = "unable to build query because ".$mysqli -> error;
        respond($response);
    }
    
    $mysqli -> close();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm creating HTML with a loop that has a column for Action. That column
I'm creating a msi based installer (using InstallShield) that has a custom action to
I've created an Audit table for an ASP.NET MVC application to track key changes
All my dynamically generated action links etc. are creating links like / A ccount/
Hello can anybody solve this please I'm creating the object in the action class
Can I access my action helpers from my models? What am avoiding is creating
How should I initiate a delete action from my view? Creating a new form-tag
The standard way of creating URLs in grails is: <a href=${createLink(controller:'news', action: 'show', params:
I've written some code for a button action. First I'm creating a button UI
Which method do you suggest and why? Creating a summary table and . .

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.