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', 'steve@equiterre.org')");
} 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', 'steve@equiterre.org')");
} 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?).