定期事件检查中的SQL错误

时间:2012-12-31 14:41:09

标签: php sql

我正在制作一个重复出现的事件系统,并且必须对检查进行硬编码以查看是否已经过了一个新事件。 (不,我不能创建一个cron作业,因为系统基础是Windows而不是,我没有访问任务调度程序。)

这是我到目前为止的代码:

<?php
require('common.php');
$query = "SELECT 
             *
          FROM 
             DD_events
      ";
try{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
$chk = $stmt->fetchall();
//print_r($chk);

foreach ($chk as $chks) {
if (time() > $chks['event_date']) {
//Add 1 day to event time
$time = strtotime($chks['event_date']);
$newTime = $time + 86400; // 24 * 60 * 60

// Create query to make the next event
    $query = "INSERT INTO
            DD_events (event_name, event_date, initiator, min_lvl, max_level)
              VALUES 
            ({$chks['event_name']}, {$newTime}, 0, {$chks['min_lvl']}, {$chks['max_level']})
      ";
    try
    {
        // These two statements run the query against your database table.
        $stmt = $db->prepare($query);
        $stmt->execute();
    }
    catch(PDOException $ex)
    {
        // Note: On a production website, you should not output $ex->getMessage().
        // It may provide an attacker with helpful information about your code. 
        die("Failed to run query: " . $ex->getMessage());
    }
}
}

它会返回此错误:

  

Failed to run query: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' 200)' at line 4

任何人都可以发现我正在制作的错误,因为我在过去的30分钟内一直在看它并且看不到它。

3 个答案:

答案 0 :(得分:2)

您需要引用您的变量,但这会使您的查询容易受到sql注入,因此正确的解决方案是使用绑定变量:

$query = "INSERT INTO
        DD_events (event_name, event_date, initiator, min_lvl, max_level)
          VALUES 
        (:event_name, :event_date, 0, :min_lvl, :max_level)
  ";
try
{
    // These two statements run the query against your database table.
    $stmt = $db->prepare($query);
    $stmt->execute(array(':event_name' => $chks['event_name'],
                         ':event_date' => $newTime,
                         ':min_lvl' => $chks['min_lvl'],
                         ':max_level' => $chks['max_level']));
}

答案 1 :(得分:0)

假设event_nameVARCHAR,您需要将{$chks['event_name']}替换为'{$chks['event_name']}'。根据数据类型,event_date

也可能适用

答案 2 :(得分:0)

也许更简单的方法来做同样的事情:

INSERT INTO DD_events
(event_name, event_date, initiator, min_lvl, max_level)
SELECT event_name, DATE_ADD(event_date, INTERVAL 1 DAY), 0, min_lvl, max_lvl
FROM DD_events

这将在一天后为每个现有事件创建一个新事件(这就是你所说的代码应该做的事情)并且基本上不需要你的整个脚本