I would like to know if this is the correct way to use try/catch
when dealing with multiple MySQL queries and PDO:
try {
$create = $con[$_POST['user-selected-connection']]->query("...");
KD::notice('success','table successfully created');
try {
$insert = $con[$_POST['user-selected-connection']]->query("...");
KD::notice('success','table was populated successfully');
} catch(PDOException $e) {
KD::notice('error','was unabled to insert records'.$e->getMessage());
}
} catch(PDOException $e) {
KD::notice('error','The table was not created.'.$e->getMessage());
}
This is part of a get started wizard in my application, and this is the part where the user needs to create tables in order to proceed. That can be done in two ways; either copy/paste the provided SQL query manually into their MySQL handler (e.g. phpMyAdmin), or by just clicking a button if they have created a user with CREATE
privileges in the previous step. (The previous step, which is "set up database, and add users into the application", tells them the benefits of having a super user for future tasks).
Anyway, I need to use try/catch
since the user has the ability to chose which user they want to use when creating the tables. And if the selects user doesn't have the required privileges, a fatal error message is returned. That's how I figured I needed to use try/catch
to handle the fatal error, and notify that the user didn't have access.
I do this task in two stages to make sure that the required records actually gets inserted after the table is created. (had a few test runs where the table was created, and the records wasn't inserted when in the same query).
Is this an appropriate way to do this?
If the create
part fails, will it jump to catch right away, or will it still try to execute the insert
query before throwing the error?