1

我正在尝试将大约 1000 条记录惰性化到 MySQL 中。但是我在下面的尝试仅在第一个查询中“插入”。之后,我收到“或死”错误消息。我尝试将 if 语句更改为随机数(除五个以外),但它总是在第一次插入后死亡。我究竟做错了什么?

$i=0;
foreach(.....){
    if($>5){
        insert($name, $phone);
    }
}

function insert($n, $p){

    $dbhost = "---"; 
    $dbuser = "---";
    $dbpass = "---";
    $dbname = "---";

    $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to mysql");
    mysql_select_db($dbname);

    $query ="INSERT INTO foo (name, phone) VALUES ('$n', '$p')";
    mysql_query($query) or die('Error, query failed');  
    mysql_close();
}
4

2 回答 2

3

这是你的代码

$i=0;
foreach(.....){
    if($>5){
        insert($name, $phone);
    }
}

function insert($n, $p){

    $dbhost = "---"; 
    $dbuser = "---";
    $dbpass = "---";
    $dbname = "---";

    $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to mysql");
    mysql_select_db($dbname);

    $query ="INSERT INTO foo (name, phone) VALUES ('$n', '$p')";
    mysql_query($query) or die('Error, query failed');  
    mysql_close();
}

连接到 MySQL 只是为了插入一行,然后断开并重新连接是一项非常昂贵的操作!!!

尝试像这样重新组织它:

$dbhost = "---"; 
$dbuser = "---";
$dbpass = "---";
$dbname = "---";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to mysql");
mysql_select_db($dbname);
$i=0;
foreach(.....){
    if($>5){
        insert($name, $phone);
    }
}
mysql_close();

function insert($n, $p){
    $query ="INSERT INTO foo (name, phone) VALUES ('$n', '$p')";
    mysql_query($query) or die('Error, query failed');  
}
于 2012-04-30T19:34:53.617 回答
2

您是否收到主键错误?

于 2012-04-30T19:28:04.623 回答