user2839873
user2839873

Reputation: 309

mysql Pdo won't sort by name

I'm having trouble with sorting the rows of a database which I connected via a pdo object. It just won't sort. I want to sort by the productnames(varchar). hopefully someone can help me

here's the code:

[...]

$db = new PDO($serverPDO, $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

[...]

if ($_SESSION['sorted'] == 1) {
    $ordered = $db->query("SELECT * FROM `produkte` ORDER BY 'produkte.preis'");
while ($order = $ordered->fetch(PDO::FETCH_ASSOC)) {
    echo "<tr>";
    echo "<td style='border-bottom:1px solid #000000;padding:20px'>".$order['produkte.name']."</td>";
    echo "<td style='border-bottom:1px solid #000000;padding:20px'>".$order['produkte.beschreibung']."</td>";
    echo "<td style='border-bottom:1px solid #000000;padding:20px'>".$order['produkte.preis']." Euro</td>";
}           
} else {
    [...]

Upvotes: 0

Views: 134

Answers (2)

Pekka
Pekka

Reputation: 449485

'produkte.preis'

in single quotes will be interpreted as a string value, probably the equivalent of order by 1 resulting in no meaningful ordering at all.

Use backticks:

`produkte.preis`

Upvotes: 2

vee
vee

Reputation: 38645

Remove the single quotes from around produkte.preis in your order by clause or escape table name and column name with backtick:

Without escaping (as it's not necessary):

$ordered = $db->query("SELECT * FROM `produkte` ORDER BY produkte.preis");

Escaping with backticks:

$ordered = $db->query("SELECT * FROM `produkte` ORDER BY `produkte`.`preis`");

You need to escape table names and column names if they are one of the MySQL Reserved words.

Upvotes: 2

Related Questions