MySQL插入语句不会插入?

时间:2013-10-29 15:27:15

标签: php mysql sql database sql-insert

我在下面附上了我的PHP代码。它正确计算累积值并正确构建SQL语句(由echo $sql;测试)。然而,进入MySQL的instert声明是不成功的。有什么想法吗?

<?php 
ini_set('memory_limit', '500M');
set_time_limit(1800);
$dbh = new mysqli('localhost','user','password','database') or die(mysql_error());
$query = "SELECT * FROM table1 ORDER BY id, date";
$del = "DELETE FROM table2";
$dbh->query($del);
if ($dbh->multi_query($query)){
    if ($result = $dbh->store_result()){
        $id = 0;
        while ($row = $result->fetch_row()){
            $date = $row[0];
            $cvalue = $row[2];
            $id = $row[1];
            $cumulative = 0;
            // Pull most recent cumulative value 
            $sql_recent = "SELECT * FROM table2 WHERE id = $id ORDER BY date DESC LIMIT 1";
            if ($dbh->multi_query($sql_recent)){
                if ($result_recent = $dbh->store_result()){
                    while ($row_recent = $result_recent->fetch_row()){
                        if($row_recent[0] != $date){
                            $cumulative = $row_recent[2];
                        }
                    }
                }
            }
            $cumulative += $cvalue;
            $sql = 'INSERT INTO table2 (id, date, cumulative) VALUES (';
            $sql .= "'".$row[1]."',";
            $sql .= "'".$date."',";
            $sql .= "'".$cumulative."',";
            $sql .= ')';
            $dbh->query($sql);
            echo $sql;
        }
    }
}
$dbh->close();
?>

2 个答案:

答案 0 :(得分:5)

在最后一个值后面有一个额外的逗号:

$sql .= "'".$cumulative."',";

尝试删除:

$sql .= "'".$cumulative."'";

答案 1 :(得分:1)

$ cumulative之后的逗号会使语法错误。