只有一条带TRUNCATE INSERT的记录查询

时间:2015-06-03 09:32:18

标签: php mysql

我的查询有问题。实际上,我想截断一个表,然后将数据插入到同一个表中。

我的问题:当我执行这两个查询时,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);
    }
?>

2 个答案:

答案 0 :(得分: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);
?>

停止!不要再使用mysql_query()了。看http://php.net/manual/en/function.mysql-query.php处的大红框?改为使用MySQLi或PDO。

答案 1 :(得分:0)

我认为你应该从foreach()循环中删除mysql_close。

第一次插入后,您正在关闭数据库连接。下一个查询将无效