Skip to content

Instantly share code, notes, and snippets.

@terrymun
Last active August 29, 2015 14:27
Show Gist options
  • Save terrymun/cb1d1405e99da9c82e7b to your computer and use it in GitHub Desktop.
Save terrymun/cb1d1405e99da9c82e7b to your computer and use it in GitHub Desktop.
Fetching data from MySQL database
<?php
// Assuming that database connection is already open
// Prepare statement
$stmt = $db->prepare("SELECT
COUNT(user_id) AS UserCount,
country AS Country
FROM users
GROUP BY country
ORDER BY country");
// Execute statement, check if execution is ok
if($stmt->execute()) {
// Fetch rows as arrays indexed by column name
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// Access field values by column name
echo $row['UserCount'] . ' user(s) in ' . $row['Country'];
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment