2015-06-03 21 views
0

我遇到查詢問題。事實上,我想截斷一個表,然後將數據插入到同一個表中。只有一條記錄帶有TRUNCATE INSERT查詢

我的問題:當我執行這2個查詢INSERT記錄只有一行,我不知道爲什麼。當我工作正常之前執行沒有TRUNCATE的INSERT查詢。我能做些什麼來結合TRUNCATE和INSERT?

感謝

下面是代碼:

<?php 
    $base = mysql_connect ("***", "***", "***"); 
    mysql_select_db ('***', $base) ; 
    $vider = "TRUNCATE TABLE drag"; 
    mysql_query($vider);   
    // accept JSON parameter (and Un-quote string if needed) 
    $p = stripslashes($_REQUEST['p']); 
    // decode JSON object (it shouldn't be decoded as associative array) 
    $arr = json_decode($p); 
    // open loop through each array element 
    foreach ($arr as $p){ 
     // set id, row index and cell index 
     $id = $p[0]; 
     $row = $p[1]; 
     $cell = $p[2]; 
     // instead of print, you can store accepted parameteres to the database 
     print "Id=$id Row=$row Cell=$cell<br>"; 
     $ajout = "INSERT INTO drag VALUES('','$id','$row','$cell')"; 
     mysql_query($ajout); 
     mysql_close($base); 
    } 
?> 

回答

0

我認爲你應該從foreach()循環中刪除mysql_close。

您正在關閉第一次插入後的數據庫連接。接下來的查詢將不會做任何事

1

我相信你需要把mysql_close()外循環。否則,如果沒有mysql_connect,您將無法發送後續查詢。

<?php 
    $base = mysql_connect ("***", "***", "***"); 
    mysql_select_db ('***', $base) ; 
    $vider = "TRUNCATE TABLE drag"; 
    mysql_query($vider);   
    // accept JSON parameter (and Un-quote string if needed) 
    $p = stripslashes($_REQUEST['p']); 
    // decode JSON object (it shouldn't be decoded as associative array) 
    $arr = json_decode($p); 
    // open loop through each array element 
    foreach ($arr as $p){ 
     // set id, row index and cell index 
     $id = $p[0]; 
     $row = $p[1]; 
     $cell = $p[2]; 
     // instead of print, you can store accepted parameteres to the database 
     print "Id=$id Row=$row Cell=$cell<br>"; 
     $ajout = "INSERT INTO drag VALUES('','$id','$row','$cell')"; 
     mysql_query($ajout); 
    } 

    mysql_close($base); 
?> 

STOP!不要再使用mysql_query()了。看到在http://php.net/manual/en/function.mysql-query.php大紅色框?改爲切換到MySQLi或PDO。