문제

I've got a 'contact' table in my database which stores the emails people are sending to me. In my adminpanel I'd like to order them by status. My contact table has an 'answered' INT column which updates as soon as I'm replying to them. Once I answered the email, the 'answered' will be set to '1' in the database.

As I said, I'd like to order the emails in my adminpanel by the 'answered' status. So all emails which arnt answered yet ('0' in database) should be on top and the emails I already have answered ('1' in database) should be on the bottom.

This is how I've currently got it:

$showTheEmails = array(); 
$getEmails = mysqli_query($mysqli,"SELECT * FROM contact ORDER BY 'answered' ASC") OR die (mysqli_error($mysqli));
if (mysqli_num_rows($getEmails) > 0){
    while($row = mysqli_fetch_array($getEmails)){
        $row = array( 
        'contact_id' => $row['contact_id'],
        'name' => $row['name'], 
        'email' => $row['email'], 
        'subject' => $row['subject'], 
        'timestamp' => $row['timestamp'], 
        'answered' => $row['answered'] );
        $showTheEmails[] = $row;
    }
}

And ofcourse the code what displays the array.

Problem is: it's not ordering correctly. What am I doing wrong? :(

도움이 되었습니까?

해결책

By wrapping with single quotes, you've created the problem. You're instructing MySQL to try to order by the word "answered" (rather than the column in the database). Simply remove the quotes.

SELECT * FROM contact ORDER BY answered ASC

As pointed out in the comments, you may also surround the column names with `backticks` like

SELECT * FROM `contact` ORDER BY `answered` ASC

Backticks are to be used for table and column identifiers, but are only necessary when the identifier is a MySQL reserved keyword, or when the identifier contains whitespace characters or characters beyond a limited set (see below) It is often recommended to avoid using reserved keywords as column or table identifiers when possible, avoiding the quoting issue.

When to use single quotes, double quotes, and backticks in MySQL

다른 팁

SELECT * FROM contact ORDER BY 'answered' ASC

The single quotes delimit a string; you're essentially giving each record a constant ordering hint, resulting in no ordering at all!

To name a field, use backticks:

SELECT * FROM contact ORDER BY `answered` ASC
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top