【问题标题】:Only one record with a TRUNCATE INSERT queries只有一条带有 TRUNCATE INSERT 查询的记录
【发布时间】:2015-08-17 10:19:48
【问题描述】:

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

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

【问题讨论】:

    标签: php mysql


    【解决方案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。

    【讨论】:

      【解决方案2】:

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

      您将在第一次插入后关闭数据库连接。下一个查询什么也不做

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-28
        • 1970-01-01
        • 1970-01-01
        • 2020-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多