循环插入查询工作一次,但不能以后


Loop insert query works once but not after

我有这个在循环外插入查询以节省内存

$z = "";
foreach($link as $i)
{
//some stuff
$z .= "('" . $s . "', '" . $data . "', '" . $data2    ."'), ";
}
$z = substr($z, 0, strlen($z) - 2);
mysql_query("INSERT INTO table VALUES ".$z."");

如果循环只循环1任何东西之后,我得到一个mysql错误,是有什么问题吗?

请使用以下格式

$inserts = array();  foreach ($link as $i)
$inserts[] = "('','$s','$data')";
$query = "INSERT INTO table VALUES ". implode(", ", $inserts);
mysql_query($query) or die(mysql_error());

这样做的一种方法是使用对象进行插入。这允许在数量太大时分批插入,最后的插入可以在destruct方法中完成。

像这样:-

<?php
$InsertClassExample = new InsertClassDemo($db);
foreach($link as $i)
{
    //some stuff
    $InsertClassExample->InsertItem($s, $data, $data2);
}
unset($InsertClassExample);
class InsertClassDemo
{
    var $db = '';
    var $InsertArray = array();
    function __CONSTRUCT($db)
    {
        $this->db = $db;
    }
    function __DESTRUCT()
    {
        if (count($this->InsertArray) > 0)
        {
            $this->PerformInsert();
        }
    }
    public function InsertItem($s, $data, $data2)
    {
        $this->InsertArray[] = "('" . $s . "', '" . $data . "', '" . $data2    ."'), ";
        if (count($this->InsertArray) > 250)
        {
            $this->PerformInsert();
        }
    }
    private function PerformInsert()
    {
        $query = "INSERT INTO table VALUES ".implode(",", $this->InsertArray);
        if($this->db->query($query) === false)
        {
            die("Insert Into table Failed - ".$this->db->error());
        }
        $this->InsertArray = array();
    }
}
?>
相关文章: