2013-10-29 191 views
0

我附上了我的PHP代碼。它會正確計算累積值並正確構建SQL語句(由echo $sql;進行測試)。但是,MySQL的instert語句不成功。有任何想法嗎?MySQL插入語句不會插入?

<?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(); 
?> 
+1

你的數據庫結構如何,哪些錯誤會引發你,等等... – vivoconunxino

+0

你能解決你的問題嗎? –

+0

是的!你的解決方案工作,這是一個簡單的錯誤,我沒有看到。 – user2932733

回答

5

你的最後一個值後多餘的逗號:

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

嘗試移除:

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

這個$ sql。=')'需要是$ sql。='),'?該語句將需要例如INSERT INTO(c1,c2)VALUES('1','2'),('3','4'); –

+0

哦,我只是意識到它只有一排。無視我的評論。 –

1

後$累計逗號會使語法錯誤。