Okay, spent some time turning this into a refactoring tutorial of sorts. 🙂
[EDIT]Just noticed that you used $database in a couple places where you should have used $stmt. Editing it here in my re-factored code section....[/EDIT]
First impressions:
function makeActive()
{
try { // I would not try/catch within a function, let the app do that
$database = new Database; // I would pass this in, rather than depend on it
$text = ""; // this variable serves no purpose
$activecode = $_GET["activecode"]; // I would pass this in, rather than depend on it
$setActive = "UPDATE username SET active = '1', activecode = 'Active' WHERE activecode = :activecode";
$stmt = $database->query($setActive);
$database->bind(':activecode', $activecode);
$database->execute();
$database->rowCount(); // no need to do this twice
// in the if/else, you are doing HTML output from a makeActive() function, meaning
// the function is doing more than that. Instead, I would just return a result indicator
// that the main app (or other output function) could use to inform the user of the result
// as desired. Keep your functions narrowly focused when possible.
if ($database->rowCount() === 1) {
return $text .="Your account is now active" . "<br><a href='index.php'>Home page</a>";
header("refresh:10; url=index.php");
} else {
return $text .="Your account is already active" . "<br><a href='index.php'>Home page</a>";
header("refresh:10; url=index.php");
}
} catch (Exception $e) {
return $text .= "Something went wrong contact site administrator" . "<br><a href='index.php'>Login page</a>";
header("refresh:10; url=index.php");
}
}
My initial pass at re-factoring it to something more like I would prefer, to keep the function focused only on its job of activating a user as well as generally DRYing things up:
/**
* Activate a user
*
* @param PDO $database
* @param string $activatecode
* @return Boolean true: successfully activated, false: already activated
*/
function makeActive(PDO $database, $activatecode)
{
$setActive = "UPDATE username SET active = '1', activecode = 'Active' WHERE activecode = :activecode";
$stmt = $database->query($setActive);
$stmt->bindParam(':activecode', $activecode); // that's the method you really want (assuming PDO?)
$stmt->execute();
return (bool) $stmt->rowCount();
}
// app code...
try {
$db = new Database;
if (makeActive($db, $_GET['activecode'])) {
echo "Your account is now active";
}
else {
echo "Your account is already active";
}
echo "<br><a href='index.php'>Home page</a>" // D.R.Y.!
}
catch(PDOException) {
// whatever you want to do if you get a DB error
}
catch(Exception) {
// whatever you want to do with other exceptions
}
finally {
header("refresh:10; url=index.php");
}