PDOStatement :: execute,如何执行?

时间:2017-07-26 01:34:55

标签: php mysql pdo

如何执行此查询?

$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM attendancy 
          WHERE user_id = $user_id 
          AND date = '$date'";
$q = $pdo->prepare($sql);

1 个答案:

答案 0 :(得分:3)

execute,您需要使用execute功能。 prepare函数的这种用法也不安全,每个变量都应该是一个占位符。

$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM attendancy 
      WHERE user_id = ? 
      AND date = ?";
$q = $pdo->prepare($sql);
$q->execute(array($user_id, $date));
while($result = $q->fetch(PDO::FETCH_ASSOC)) {
     print_r($result);
}