I need to pull out all the entries in my database that relate to a certain user_id, order them by the time they were entered into the database (this is php unix time() seconds) and then group them by surname so that they sit with entries of the same surname.
This is the query so far.. Although it only gives me a certain amount of entries.
$sql = "SELECT * FROM people WHERE user_token='$user_token'
ORDER BY time GROUP BY surname";
What is the correct way to use ORDER and GROUP by in order to get all of the results out grouped by the surname but ordered by the time the were entered? Thanks.
You have an error in your SQL, syntax, SQL-injection vulnerability and probably you are using obsolete database extension. So, here is what it should really look like:
$dsn = "mysql:dbname=$db_name;host=$db_host";
try{
$pdo = new PDO($dsn, $username, $password);
}
catch(PDOException $e){
die($e->getMessage());
}
$sql = "SELECT surname, count(id) FROM people WHERE user_token=:usr_token ORDER BY time GROUP BY surname";
$stmt = $pdo->prepare($sql);
if ($stmt->execute(array(':usr_token'=>$user_token))){
$result = $stmt->fetchAll();
}
else{
print_r($stmt->errorInfo());
die("Error executing query");
}
Refer to PDO manual for details
The ORDER BY
clause should be the last, but you have to specify fields to be aggregated.
Such as:
SELECT surname, count(*)
FROM people
WHERE user_token='$user_token'
GROUP BY surname
ORDER BY surname
精彩评论