I have this table structure,
| id | name | level |
---------------------
| 1 | a | 1 |
| 2 | b | 2 |
| 3 | c | 3 |
| 5 | d | 4 |
| 6 | e | 1 |
| 7 | f | 2 |
| 8 | g | 1 |
| 9 | g | 4 |
I want to order my fetch result to level, so I execute this query:
$sql = "SELECT * FROM section_tb WHERE id = ? ORDER BY level";
$stmt = $db->prepare($sql);
$stmt->execute(array($id));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
However when I print_r($result) the order seems like it was sorted by id. I am confused why.
My db details:
id - PRIMARY, AUTO INCREMENT
name - UNIQUE
INNODB
Your query is ordering correctly.
This is irrelevant since it’s only returning one row each time its called anyway.
Your foreach is calling into it multiple times, and the ordering only affects the actual database call. Therefore the overall order of the results is the order of that foreach.
If the foreach had passed a parameter that identified more than one row, then within each of those calls the order would be by level (e.g. if you’d done queries to match on name, then the two that match “g” would be in the order requested).
You want to change the query to something like
SELECT * FROM section_tb WHERE id in (1,2,3,4,5,6,7,8,9) ORDER BY level(or perhaps justSELECT * FROM section_tb ORDER BY level), call it once, and loop through the results.