开发者

SELECT * FROM people WHERE user_id='$user_id' ORDER BY time GROUP BY surname [closed]

It's difficult to tell what is being as开发者_高级运维ked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜