$stmt->execute() : How to know if db insert was successful?












30















With the following piece of code, how do i know that anything was inserted in to the db?



if ($stmt = $connection->prepare("insert into table (blah) values (?)")) {
$stmt->bind_param("s", $blah);
$stmt->execute();
$stmt->close();
}


I had thought adding the following line would have worked but apparently not.



if($stmt->affected_rows==-1){$updateAdded="N"; echo "failed";}  


And then use the $updatedAdded="N" to then skip other pieces of code further down the page that are dependent on the above insert being successful.



Any ideas?










share|improve this question























  • Wouldn't affected_rows be 0 if nothing had been inserted? Although if nothing had been inserted it would presumably be because execute had failed. Have you tried if ($stmt->affected_rows < 1)?

    – MichaelRushton
    Apr 3 '12 at 11:02
















30















With the following piece of code, how do i know that anything was inserted in to the db?



if ($stmt = $connection->prepare("insert into table (blah) values (?)")) {
$stmt->bind_param("s", $blah);
$stmt->execute();
$stmt->close();
}


I had thought adding the following line would have worked but apparently not.



if($stmt->affected_rows==-1){$updateAdded="N"; echo "failed";}  


And then use the $updatedAdded="N" to then skip other pieces of code further down the page that are dependent on the above insert being successful.



Any ideas?










share|improve this question























  • Wouldn't affected_rows be 0 if nothing had been inserted? Although if nothing had been inserted it would presumably be because execute had failed. Have you tried if ($stmt->affected_rows < 1)?

    – MichaelRushton
    Apr 3 '12 at 11:02














30












30








30


6






With the following piece of code, how do i know that anything was inserted in to the db?



if ($stmt = $connection->prepare("insert into table (blah) values (?)")) {
$stmt->bind_param("s", $blah);
$stmt->execute();
$stmt->close();
}


I had thought adding the following line would have worked but apparently not.



if($stmt->affected_rows==-1){$updateAdded="N"; echo "failed";}  


And then use the $updatedAdded="N" to then skip other pieces of code further down the page that are dependent on the above insert being successful.



Any ideas?










share|improve this question














With the following piece of code, how do i know that anything was inserted in to the db?



if ($stmt = $connection->prepare("insert into table (blah) values (?)")) {
$stmt->bind_param("s", $blah);
$stmt->execute();
$stmt->close();
}


I had thought adding the following line would have worked but apparently not.



if($stmt->affected_rows==-1){$updateAdded="N"; echo "failed";}  


And then use the $updatedAdded="N" to then skip other pieces of code further down the page that are dependent on the above insert being successful.



Any ideas?







php oop mysqli






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Apr 3 '12 at 10:59









cosmicsafaricosmicsafari

1,46272647




1,46272647













  • Wouldn't affected_rows be 0 if nothing had been inserted? Although if nothing had been inserted it would presumably be because execute had failed. Have you tried if ($stmt->affected_rows < 1)?

    – MichaelRushton
    Apr 3 '12 at 11:02



















  • Wouldn't affected_rows be 0 if nothing had been inserted? Although if nothing had been inserted it would presumably be because execute had failed. Have you tried if ($stmt->affected_rows < 1)?

    – MichaelRushton
    Apr 3 '12 at 11:02

















Wouldn't affected_rows be 0 if nothing had been inserted? Although if nothing had been inserted it would presumably be because execute had failed. Have you tried if ($stmt->affected_rows < 1)?

– MichaelRushton
Apr 3 '12 at 11:02





Wouldn't affected_rows be 0 if nothing had been inserted? Although if nothing had been inserted it would presumably be because execute had failed. Have you tried if ($stmt->affected_rows < 1)?

– MichaelRushton
Apr 3 '12 at 11:02












5 Answers
5






active

oldest

votes


















65














The execute() method returns a boolean ... so just do this :



if ($stmt->execute()) { 
// it worked
} else {
// it didn't
}





share|improve this answer
























  • This seems like it will work, cheers

    – cosmicsafari
    Apr 3 '12 at 11:36











  • i took a flier on using this method. i googled to make sure, and it led me to this answer. upvoted so more people will use this in their scripts.

    – r3wt
    Mar 30 '14 at 17:09






  • 3





    This does not ensure that an insert ever happened! Only that there was not an error.

    – user1032531
    Feb 9 '16 at 20:11






  • 1





    @user1032531: You are correct. An INSERT ... SELECT could insert zero rows and return successfully. In the case of OP query... INSERT INTO .. VALUES ... I'm not aware of any scenario where the statement would complete successfully without inserting a row. (It's possible I've overlooked some possibility.)

    – spencer7593
    Apr 10 '17 at 1:30



















20














Check the return value of $stmt->execute()



if(!$stmt->execute()) echo $stmt->error;


Note that line of code does perform the execute() command so use it in place of your current $stmt->execute() not after it.






share|improve this answer































    5














    Just check the manual pages of whatever function you are using:




    prepare() - returns a statement object or FALSE if an error occurred.

    bind_param() - Returns TRUE on success or FALSE on failure.

    execute() - Returns TRUE on success or FALSE on failure.

    close() - Returns TRUE on success or FALSE on failure.




    In practice, though, this gets annoying and it's error prone. It's better to configure mysqli to throw exceptions on error and get rid of all specific error handling except for the few occasions where an error is expected (e.g., a tentative insert that might violate a unique constraint):



    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);





    share|improve this answer


























    • and this for PDO: es.php.net/manual/en/book.pdo.php

      – Ömer An
      Dec 29 '18 at 9:29



















    4














    if you mean that you want to know the number of affected rows you can use rowCount on the pdo statement



    $stmt->rowCount();


    after execute;



    if you are talking about error handling I think the best option is to set the errmode to throwing exteptions and wrap everything in a try/catch block



    try
    {
    //----
    }
    catch(PDOException $e)
    {
    echo $e->getMessage();
    }





    share|improve this answer

































      0














      Other way:



      if ($stmt->error){
      echo "Error";
      }
      else{
      echo "Ok";
      }





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f9991882%2fstmt-execute-how-to-know-if-db-insert-was-successful%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        5 Answers
        5






        active

        oldest

        votes








        5 Answers
        5






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        65














        The execute() method returns a boolean ... so just do this :



        if ($stmt->execute()) { 
        // it worked
        } else {
        // it didn't
        }





        share|improve this answer
























        • This seems like it will work, cheers

          – cosmicsafari
          Apr 3 '12 at 11:36











        • i took a flier on using this method. i googled to make sure, and it led me to this answer. upvoted so more people will use this in their scripts.

          – r3wt
          Mar 30 '14 at 17:09






        • 3





          This does not ensure that an insert ever happened! Only that there was not an error.

          – user1032531
          Feb 9 '16 at 20:11






        • 1





          @user1032531: You are correct. An INSERT ... SELECT could insert zero rows and return successfully. In the case of OP query... INSERT INTO .. VALUES ... I'm not aware of any scenario where the statement would complete successfully without inserting a row. (It's possible I've overlooked some possibility.)

          – spencer7593
          Apr 10 '17 at 1:30
















        65














        The execute() method returns a boolean ... so just do this :



        if ($stmt->execute()) { 
        // it worked
        } else {
        // it didn't
        }





        share|improve this answer
























        • This seems like it will work, cheers

          – cosmicsafari
          Apr 3 '12 at 11:36











        • i took a flier on using this method. i googled to make sure, and it led me to this answer. upvoted so more people will use this in their scripts.

          – r3wt
          Mar 30 '14 at 17:09






        • 3





          This does not ensure that an insert ever happened! Only that there was not an error.

          – user1032531
          Feb 9 '16 at 20:11






        • 1





          @user1032531: You are correct. An INSERT ... SELECT could insert zero rows and return successfully. In the case of OP query... INSERT INTO .. VALUES ... I'm not aware of any scenario where the statement would complete successfully without inserting a row. (It's possible I've overlooked some possibility.)

          – spencer7593
          Apr 10 '17 at 1:30














        65












        65








        65







        The execute() method returns a boolean ... so just do this :



        if ($stmt->execute()) { 
        // it worked
        } else {
        // it didn't
        }





        share|improve this answer













        The execute() method returns a boolean ... so just do this :



        if ($stmt->execute()) { 
        // it worked
        } else {
        // it didn't
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Apr 3 '12 at 11:02









        ManseUKManseUK

        34.1k86495




        34.1k86495













        • This seems like it will work, cheers

          – cosmicsafari
          Apr 3 '12 at 11:36











        • i took a flier on using this method. i googled to make sure, and it led me to this answer. upvoted so more people will use this in their scripts.

          – r3wt
          Mar 30 '14 at 17:09






        • 3





          This does not ensure that an insert ever happened! Only that there was not an error.

          – user1032531
          Feb 9 '16 at 20:11






        • 1





          @user1032531: You are correct. An INSERT ... SELECT could insert zero rows and return successfully. In the case of OP query... INSERT INTO .. VALUES ... I'm not aware of any scenario where the statement would complete successfully without inserting a row. (It's possible I've overlooked some possibility.)

          – spencer7593
          Apr 10 '17 at 1:30



















        • This seems like it will work, cheers

          – cosmicsafari
          Apr 3 '12 at 11:36











        • i took a flier on using this method. i googled to make sure, and it led me to this answer. upvoted so more people will use this in their scripts.

          – r3wt
          Mar 30 '14 at 17:09






        • 3





          This does not ensure that an insert ever happened! Only that there was not an error.

          – user1032531
          Feb 9 '16 at 20:11






        • 1





          @user1032531: You are correct. An INSERT ... SELECT could insert zero rows and return successfully. In the case of OP query... INSERT INTO .. VALUES ... I'm not aware of any scenario where the statement would complete successfully without inserting a row. (It's possible I've overlooked some possibility.)

          – spencer7593
          Apr 10 '17 at 1:30

















        This seems like it will work, cheers

        – cosmicsafari
        Apr 3 '12 at 11:36





        This seems like it will work, cheers

        – cosmicsafari
        Apr 3 '12 at 11:36













        i took a flier on using this method. i googled to make sure, and it led me to this answer. upvoted so more people will use this in their scripts.

        – r3wt
        Mar 30 '14 at 17:09





        i took a flier on using this method. i googled to make sure, and it led me to this answer. upvoted so more people will use this in their scripts.

        – r3wt
        Mar 30 '14 at 17:09




        3




        3





        This does not ensure that an insert ever happened! Only that there was not an error.

        – user1032531
        Feb 9 '16 at 20:11





        This does not ensure that an insert ever happened! Only that there was not an error.

        – user1032531
        Feb 9 '16 at 20:11




        1




        1





        @user1032531: You are correct. An INSERT ... SELECT could insert zero rows and return successfully. In the case of OP query... INSERT INTO .. VALUES ... I'm not aware of any scenario where the statement would complete successfully without inserting a row. (It's possible I've overlooked some possibility.)

        – spencer7593
        Apr 10 '17 at 1:30





        @user1032531: You are correct. An INSERT ... SELECT could insert zero rows and return successfully. In the case of OP query... INSERT INTO .. VALUES ... I'm not aware of any scenario where the statement would complete successfully without inserting a row. (It's possible I've overlooked some possibility.)

        – spencer7593
        Apr 10 '17 at 1:30













        20














        Check the return value of $stmt->execute()



        if(!$stmt->execute()) echo $stmt->error;


        Note that line of code does perform the execute() command so use it in place of your current $stmt->execute() not after it.






        share|improve this answer




























          20














          Check the return value of $stmt->execute()



          if(!$stmt->execute()) echo $stmt->error;


          Note that line of code does perform the execute() command so use it in place of your current $stmt->execute() not after it.






          share|improve this answer


























            20












            20








            20







            Check the return value of $stmt->execute()



            if(!$stmt->execute()) echo $stmt->error;


            Note that line of code does perform the execute() command so use it in place of your current $stmt->execute() not after it.






            share|improve this answer













            Check the return value of $stmt->execute()



            if(!$stmt->execute()) echo $stmt->error;


            Note that line of code does perform the execute() command so use it in place of your current $stmt->execute() not after it.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Apr 3 '12 at 11:08









            MattPMattP

            1,97722237




            1,97722237























                5














                Just check the manual pages of whatever function you are using:




                prepare() - returns a statement object or FALSE if an error occurred.

                bind_param() - Returns TRUE on success or FALSE on failure.

                execute() - Returns TRUE on success or FALSE on failure.

                close() - Returns TRUE on success or FALSE on failure.




                In practice, though, this gets annoying and it's error prone. It's better to configure mysqli to throw exceptions on error and get rid of all specific error handling except for the few occasions where an error is expected (e.g., a tentative insert that might violate a unique constraint):



                mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);





                share|improve this answer


























                • and this for PDO: es.php.net/manual/en/book.pdo.php

                  – Ömer An
                  Dec 29 '18 at 9:29
















                5














                Just check the manual pages of whatever function you are using:




                prepare() - returns a statement object or FALSE if an error occurred.

                bind_param() - Returns TRUE on success or FALSE on failure.

                execute() - Returns TRUE on success or FALSE on failure.

                close() - Returns TRUE on success or FALSE on failure.




                In practice, though, this gets annoying and it's error prone. It's better to configure mysqli to throw exceptions on error and get rid of all specific error handling except for the few occasions where an error is expected (e.g., a tentative insert that might violate a unique constraint):



                mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);





                share|improve this answer


























                • and this for PDO: es.php.net/manual/en/book.pdo.php

                  – Ömer An
                  Dec 29 '18 at 9:29














                5












                5








                5







                Just check the manual pages of whatever function you are using:




                prepare() - returns a statement object or FALSE if an error occurred.

                bind_param() - Returns TRUE on success or FALSE on failure.

                execute() - Returns TRUE on success or FALSE on failure.

                close() - Returns TRUE on success or FALSE on failure.




                In practice, though, this gets annoying and it's error prone. It's better to configure mysqli to throw exceptions on error and get rid of all specific error handling except for the few occasions where an error is expected (e.g., a tentative insert that might violate a unique constraint):



                mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);





                share|improve this answer















                Just check the manual pages of whatever function you are using:




                prepare() - returns a statement object or FALSE if an error occurred.

                bind_param() - Returns TRUE on success or FALSE on failure.

                execute() - Returns TRUE on success or FALSE on failure.

                close() - Returns TRUE on success or FALSE on failure.




                In practice, though, this gets annoying and it's error prone. It's better to configure mysqli to throw exceptions on error and get rid of all specific error handling except for the few occasions where an error is expected (e.g., a tentative insert that might violate a unique constraint):



                mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 29 '18 at 12:56

























                answered Apr 3 '12 at 11:04









                Álvaro GonzálezÁlvaro González

                106k30185273




                106k30185273













                • and this for PDO: es.php.net/manual/en/book.pdo.php

                  – Ömer An
                  Dec 29 '18 at 9:29



















                • and this for PDO: es.php.net/manual/en/book.pdo.php

                  – Ömer An
                  Dec 29 '18 at 9:29

















                and this for PDO: es.php.net/manual/en/book.pdo.php

                – Ömer An
                Dec 29 '18 at 9:29





                and this for PDO: es.php.net/manual/en/book.pdo.php

                – Ömer An
                Dec 29 '18 at 9:29











                4














                if you mean that you want to know the number of affected rows you can use rowCount on the pdo statement



                $stmt->rowCount();


                after execute;



                if you are talking about error handling I think the best option is to set the errmode to throwing exteptions and wrap everything in a try/catch block



                try
                {
                //----
                }
                catch(PDOException $e)
                {
                echo $e->getMessage();
                }





                share|improve this answer






























                  4














                  if you mean that you want to know the number of affected rows you can use rowCount on the pdo statement



                  $stmt->rowCount();


                  after execute;



                  if you are talking about error handling I think the best option is to set the errmode to throwing exteptions and wrap everything in a try/catch block



                  try
                  {
                  //----
                  }
                  catch(PDOException $e)
                  {
                  echo $e->getMessage();
                  }





                  share|improve this answer




























                    4












                    4








                    4







                    if you mean that you want to know the number of affected rows you can use rowCount on the pdo statement



                    $stmt->rowCount();


                    after execute;



                    if you are talking about error handling I think the best option is to set the errmode to throwing exteptions and wrap everything in a try/catch block



                    try
                    {
                    //----
                    }
                    catch(PDOException $e)
                    {
                    echo $e->getMessage();
                    }





                    share|improve this answer















                    if you mean that you want to know the number of affected rows you can use rowCount on the pdo statement



                    $stmt->rowCount();


                    after execute;



                    if you are talking about error handling I think the best option is to set the errmode to throwing exteptions and wrap everything in a try/catch block



                    try
                    {
                    //----
                    }
                    catch(PDOException $e)
                    {
                    echo $e->getMessage();
                    }






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Apr 3 '12 at 11:17









                    ManseUK

                    34.1k86495




                    34.1k86495










                    answered Apr 3 '12 at 11:11









                    mishumishu

                    4,67611734




                    4,67611734























                        0














                        Other way:



                        if ($stmt->error){
                        echo "Error";
                        }
                        else{
                        echo "Ok";
                        }





                        share|improve this answer




























                          0














                          Other way:



                          if ($stmt->error){
                          echo "Error";
                          }
                          else{
                          echo "Ok";
                          }





                          share|improve this answer


























                            0












                            0








                            0







                            Other way:



                            if ($stmt->error){
                            echo "Error";
                            }
                            else{
                            echo "Ok";
                            }





                            share|improve this answer













                            Other way:



                            if ($stmt->error){
                            echo "Error";
                            }
                            else{
                            echo "Ok";
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Aug 20 '17 at 15:49









                            Pedro AntônioPedro Antônio

                            15515




                            15515






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f9991882%2fstmt-execute-how-to-know-if-db-insert-was-successful%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Callistus III

                                Ostreoida

                                Plistias Cous