$query = "SELECT 1 FROM users WHERE username = :username";
$query_params = array(':username' => $_POST['username']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if($row)
{
die("This username is already in use");
}
This all works, but:
-
Do I really need prepared statement if the query is just
SELECTorSELECT COUNT?
Because, if there is noINSERT / UPDATE / DELETEoperations on the table – I suppose there is no dangerous of sql injection or spam ? -
Do I really need
try/catchstatement each time I go to database ?
As far as connection to database goes this is the only approach you need. Try and Catch: (if you are using MySql database )
Plus, there is a built-in count query for count:
$affected_rows = $stmt->rowCount();Here is a good tutorial, if you never knew
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers