php - binding PDO mysql parameter from $_get doesn't work ← (PHP, MySQL)

Solution:

See Madra's answer.

You can't bind a column. Use a white list array of valid columns to sort against (to compare the $_GET value to) and just substitute it into the query:

$valid_cols = array('name', 'age');
$sort = 'default_sort_field';
if(isset($_GET['sort']) && in_array($_GET['sort'], $valid_cols)){
    $sort = $_GET['sort'];
}

$statement = $db->prepare("SELECT * FROM myTable ORDER BY $sort");

Answer



Solution:

Maybe because you named you variable $sort, but you're trying to bind $order?

That's because you can't bind column names with prepared statements. They're only meant to be used with values.

Instead, what you should do, is to have a set of predefined options, and sort by those. You shouldn't give the user a choice of directly ordering by a real column name.

Source