mysql_query() does not throw exceptions (and only exceptions can be caught). mysqli_ and PDO can, if you enable it to. mysql_ is also very obsolete (and has been for many years already), so use PDO or MySQLi with exception-mode enabled, and it'll work. Both these APIs support prepared statements, so you should use that too if you start inputting variables in your query.
For MySQLi, you need mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); before the connection, and for PDO you need $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
MySQLi example
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli($hostname, $username, $password, $databasename);
$mysqli->set_charset("utf8");
try {
$mysqli->query("INSERT INTO TP2_ORGANISME
VALUES ('A0A0', 'Equiterre', 1, '/photos/equiterre_logo.png', 'Steve Guilbault', '[email protected]')");
} catch (mysqli_sql_exception $e) {
if ($e->getCode() == 1062) {
// Duplicate user
} else {
throw $e;// in case it's any other error
}
}
PDO example
$pdo = new PDO("mysql:host=$hostname;dbname=$databasename;charset=utf8", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Enables exception mode
try {
$pdo->query("INSERT INTO TP2_ORGANISME
VALUES ('A0A0', 'Equiterre', 1, '/photos/equiterre_logo.png', 'Steve Guilbault', '[email protected]')");
} catch (PDOException $e) {
if ($e->getCode() == 1062) {
// Duplicate user
} else {
throw $e;// in case it's any other error
}
}
When you start introducing variables into your queries, look into using a prepared statement (How can I prevent SQL injection in PHP?).
mysql_queryinterface which was removed in PHP 7. A replacement like PDO is not hard to learn and a guide like PHP The Right Way helps explain best practices. Here parameters are NOT properly escaped and this has severe SQL injection bugs in this code. Escape any and all user data, especially from$_POSTor$_GET.mysql_queryis no longer available, and besides, you can't insert data like that. You'll need to work through a basic SQL primer before any of this is going to make much sense, or use a database abstraction layer like e RedBeanPHP, Doctrine, Propel or Eloquent for a softer start.