我最近在PHP中遇到了PDO预处理语句的问题。我试图从MySQL表中获取一些结果,并按照在start_time
列中输入的时间对它们进行排序。
这是我现在正在运行的代码:
class DatabaseTable {
private $table;
private $pdo;
public function __construct($pdo, $table) {
$this->pdo = $pdo;
$this->table = $table;
}
public function findMany2ordered($field, $value, $field2, $value2, $order, $direction) {
$stmt = $this->pdo->prepare('SELECT * FROM ' . $this->table . ' WHERE '.$field.' = :value AND '.$field2.' = :value2 ORDER BY :order :direction' );
$criteria = [
'value' => $value,
'value2' =>$value2,
'order' =>$order,
'direction' =>$direction
];
//$stmt->execute($criteria);
//return $stmt->fetch();
if($stmt->execute($criteria)){
return $stmt->fetchAll();
}else{
return $stmt->errorInfo()[2];
}
}
}
在此之后,我实例化了这个类:
$slots = new DatabaseTable($pdo, 'slots');
然后我尝试查询值并按时间排序:
$timeline = $slots->findMany2ordered('user_id', $_SESSION['user_id'], 'slot_date', $_POST['timelinedate'], 'start_time', 'ASC');
然后我有一个foreach循环,它遍历它们并在页面上回显结果:
foreach ($timeline as $slot){
$taskDetails = $tasks->find('task_id', $slot['task_id']);
//var_dump($taskDetails);
echo'<div class="slot"';
echo'<h3>'. $taskDetails['task_title']. '<h3>';
echo'<span> start time:'.$slot['start_time'].' </span>';
echo'</div>';
}
页面上打印时结果仍然无序:
有没有人偶然发现过这个?有解决方案吗?
先谢谢你的帮助。
答案 0 :(得分:1)
由于PDO参数不能用于表名和列名,因此最好以表/列名和排序顺序指定为PHP变量和任何可能的文字来编写查询字符串。用于将值用作占位符/有界参数。
因此,您的功能类似于:
public function findMany2ordered($field, $value, $field2, $value2, $order, $direction) {
$stmt = $this->pdo->prepare('SELECT * FROM ' . $this->table
. ' WHERE '.$field.' = :value '
. ' AND '.$field2.' = :value2 '
. ' ORDER BY '.$order .' '. $direction );
$criteria = [
':value' => $value,
':value2' => $value2
];
if($stmt->execute($criteria)){
return $stmt->fetchAll();
}else{
return $stmt->errorInfo()[2];
}
}