-1

I am inserting data into a table using PHP and want to find out if the SQL has worked properly so I can display a success message. Is there a way of returning success from SQL back to PHP after the statement is executed.

    function addPlayer($playerName, $dateOfBirth, $team) {
       $sql = "INSERT INTO players VALUES (DEFAULT, :name, :teamID, :dob)";
       $stmt = $this->connection->conn->prepare($sql);
       $stmt->bindParam(":name", $playerName);
       $stmt->bindParam(":dob", $dateOfBirth);
       $stmt->bindParam(":teamID", $team);
       $stmt->execute();
    }

I want to know if the execute statement has been successful and the data added to the table. Is there a way to have the SQL return a success or fail so I can display an error or success message on the page?

6C69616D
  • 72
  • 10
  • How do you have the `PDO::ATTR_ERRMODE` option set? – Barmar Aug 27 '19 at 21:01
  • See https://www.php.net/manual/en/pdo.error-handling.php – Barmar Aug 27 '19 at 21:02
  • I haven't set it to anything myself so I assume it is the default value. However, I thought this was for PDO errors not returning the success of an SQL query, as a failed SQL query may not always throw a PDO error? – 6C69616D Aug 27 '19 at 21:09
  • It depends on what you mean by "failed". It's not usually an error if a `SELECT` doesn't find any matching rows, or `UPDATE` doesn't find anything to update. – Barmar Aug 27 '19 at 21:14
  • No, but sometimes Insert can fail due to a wrong data type being entered or the fact that the referential integrity of the table isn't being fulfilled. This doesn't throw an error for me. Would this be the case if I changed the error handling? – 6C69616D Aug 27 '19 at 21:17
  • 2
    The default error mode is to just return `FALSE` rather than throw an error. I suggest you enable `PDO::ERRMODE_EXCEPTION` and use `try/catch` to report errors. – Barmar Aug 27 '19 at 21:18
  • I'll try that and see if I can find the solution. If I am correct though this is for development only and not for the release of any software? – 6C69616D Aug 27 '19 at 21:20
  • 2
    No, you definitely need it in production, so the script will stop if there's a problem. – Barmar Aug 27 '19 at 21:21
  • Understood, Thanks for the help – 6C69616D Aug 27 '19 at 21:22

1 Answers1

-1
   $sql = "INSERT INTO players VALUES (DEFAULT, :name, :teamID, :dob)";
       $connect= $this->connection->conn;
        $stmt= $connect->prepare($sql);
       $stmt->bindParam(":name", $playerName);
       $stmt->bindParam(":dob", $dateOfBirth);
       $stmt->bindParam(":teamID", $team);
       return   (   $stmt->execute()  && $connect->rowCount()>0);



Or shortly

     $stmt->execute();
    if ($stmt->rowCount() > 0)
    {
        return true;
    }

dılo sürücü
  • 3,821
  • 1
  • 26
  • 28