I want to understand why the following happens:
I have in a PHP file (index.php) the instantiation of a class and the use of the method register()
. The issue is that try catch
it doesn't take the exceptions and even though the record is not made in the database if it increases the auto-increment of the id. It doesn't matter if I write the query wrong, or if I try to insert records with repeated fields in a field of type UNIQUE
. Below is the evidence. Basically I want to understand why the catch is not executed and all the try is executed even though there are errors with the Query, it doesn't matter if I use Throwable, Exception or PDOException.
index.php code:
<?php
require 'src/Classes/Account.php';
$reg = new Account();
$reg->register('Alfredossss', 'Serranosss', 'Prueba2sss');
echo "Registro Satisfactorio";
This instantiation comes from the Account class
Account.php code:
<?php
require_once 'database/Conexion.php';
class Account
{
public function register($username, $password, $email)
{
$pdo = Conexion::openConnection();
$sql = "INSERT INTO account (username, password, email, created_on) VALUES (?,?,?,now())";
try {
$pdo->beginTransaction();
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password, $email]);
$pdo->commit();
Conexion::closeConnection();
} catch (\Throwable $th) {
echo "Mensaje de Error: " . $th->getMessage();
}
}
}
Which in turn connects to the database/Connection.php file of the Connection class
Code Connection.php:
class Conexion
{
public static $db;
private static $user = '*****';
private static $password = '****';
public static function openConnection()
{
return self::$db = new PDO('pgsql:host=localhost;dbname=ajax', self::$user, self::$password);
}
public static function closeConnection()
{
self::$db = null;
}
}
SQL code:
CREATE TABLE account(
user_id serial PRIMARY KEY,
username VARCHAR (50) UNIQUE NOT NULL,
password VARCHAR (50) NOT NULL,
email VARCHAR (355) UNIQUE NOT NULL,
created_on TIMESTAMP NOT NULL,
last_login TIMESTAMP
);
I think I found out why you don't get the catch, add the attributes PDO::ATTR_ERRMODE: and PDO::ERRMODE_EXCEPTION to your connection for error reporting:
Leave it this way, any errors you have in the query will be skipped.
In the function, try this way as the partner says: