php查询忽略顺序

时间:2014-06-29 14:15:08

标签: php mysql sql pdo

我试图显示10行并按照最高分排序,代码运行时没有错误,但它仍然按照它们在数据库中出现的顺序显示它们。

$questionScore = query('SELECT * FROM questions ORDER BY score = :score DESC LIMIT 10',
array('score' => ['score']),
$conn);

这是我的查询声明 -

function query($query, $bindings, $conn)
{
   $stmt = $conn->prepare($query);
   $stmt->execute($bindings);

   $results = $stmt->fetchAll();

   return $results ? $results : false;
}

我的功能

1 个答案:

答案 0 :(得分:1)

这是你的功能,迫使你在没有必要时设置绑定

$questionScore = query(
    'SELECT * FROM questions ORDER BY score DESC LIMIT 10',
    array(),
    $conn
);


function query($query, $bindings, $conn)
{
   $stmt = $conn->prepare($query);
   if (!empty($bindings))
       $stmt->execute($bindings);

   $results = $stmt->fetchAll();

   return $results ? $results : false;
}

甚至重新组织函数的参数,因此如果不需要,则不需要传递空绑定:

$questionScore = query(
    'SELECT * FROM questions ORDER BY score DESC LIMIT 10',
    $conn
);


function query($query, $conn, $bindings = array())
{
   $stmt = $conn->prepare($query);
   if (!empty($bindings))
       $stmt->execute($bindings);

   $results = $stmt->fetchAll();

   return $results ? $results : false;
}