MySQLi到PDO问题与准备好的语句

时间:2013-05-16 05:59:15

标签: php mysql pdo

尝试迁移到PDO并拥有helluva时间。这是我的代码,它不能正常工作:

$db = new PDO('mysql:host=localhost;dbname=pp_production;charset=utf8', 'mr', 'jones');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$report_date = "DATE(time_track.punch_in) = CURRENT_DATE ORDER BY time_track.punch_in DESC";

$query_clock_history = $db->prepare("SELECT time_track.id, time_track.job_id, first_name, activity, time_track.comments, time_track.punch_in, time_track.punch_out, TIMESTAMPDIFF(MINUTE, time_track.punch_in, time_track.punch_out) AS time_spent, customers.customer_name, typesetting.description, typesetting.job_ticket FROM typesetting 
JOIN time_track ON typesetting.id = time_track.job_id 
JOIN employees ON employees.id = time_track.employee_id 
JOIN activities ON activities.id = time_track.activity_id 
JOIN customers ON customers.id = typesetting.customers_id 
WHERE :report_date");
$query_clock_history->bindValue(':report_date', $report_date, PDO::PARAM_STR);
$query_clock_history->execute();

因此,没有结果。如果我将$ report_date替换为$ report_date变量的实际内容,则它可以正常工作。我一直在敲打这个问题已经有一段时间了,只是无法让它发挥作用。任何帮助非常感谢。这是在MAMP上运行,如果这有所不同。

尝试了一些不起作用的事情

$report_date = "CURRENT_DATE";
...
WHERE DATE(time_track.punch_in) = :report_date ORDER BY time_track.punch_in DESC");

仍然没有。这似乎是一个简单的例子,但我不知道为什么它不起作用。

2 个答案:

答案 0 :(得分:0)

您无法绑定任意查询部分,只能绑定标量值(即字符串和数字),PDO或mysqli

尽管如此,您根本不需要对此查询进行任何绑定

$sql = "SELECT time_track.id, time_track.job_id, first_name, activity, time_track.comments, time_track.punch_in, time_track.punch_out, TIMESTAMPDIFF(MINUTE, time_track.punch_in, time_track.punch_out) AS time_spent, customers.customer_name, typesetting.description, typesetting.job_ticket FROM typesetting 
JOIN time_track ON typesetting.id = time_track.job_id 
JOIN employees ON employees.id = time_track.employee_id 
JOIN activities ON activities.id = time_track.activity_id 
JOIN customers ON customers.id = typesetting.customers_id 
WHERE DATE(time_track.punch_in) = CURRENT_DATE ORDER BY time_track.punch_in DESC"

$stmt = $db->prepare($sql);
$stmt->execute();

这就是全部

答案 1 :(得分:0)

你的地方必须有条件,即

WHERE date = :report_date

来自php网站

$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();

因此,您的:report_date参数需要在查询语句中对您的表中的colomn输入条件