2

我想知道如何更改下面的代码以读取 x 行仅处理 sql insert 语句,然后继续按 x 数读取文件并处理直到文件结束。我对文件指针的想法很陌生,但我知道使用 fgets 应该是可能的。

我希望将下面的代码更改为一个函数,我可以在其中传递文件名和要读取和处理的行数。

我目前有:(从这里

$handle = fopen(dirname(__FILE__)."/files/workorderstest.csv" , "r");

$batch++;

if ($handle) {
    $counter = 0;

    //instead of executing query one by one,
    //let us prepare 1 SQL query that will insert all values from the batch

    $sql ="INSERT INTO workorderstest(id,parentid,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10) VALUES ";

    while (($line = fgets($handle)) !== false) {
       $sql .= "($line),";
       $counter++;
    }

    $sql = substr($sql, 0, strlen($sql) - 1);

    var_dump($sql);

    if ($conn->query($sql) === TRUE) {

    } else {

    }

    fclose($handle);
}

我想将内存占用保持在最低限度。我认为这应该只是跟踪指针的问题->重复直到到达行->处理sql->从指针开始->重复直到eof。

  1. fgets()最好用这个吗?
  2. 我是否需要合并一个回调或一些类似的东西来推迟 sql 处理,直到所有行都被读取?
  3. 由于我仍在学习 PHP,我有点迷失从哪里开始。

**** 如果对其他人有帮助,请在下面更新已回答的脚本...

date_default_timezone_set('Australia/Brisbane');
$date = date('m/d/Y h:i:s a', time());
$timezone = date_default_timezone_get();
$time_start = microtime(true);

$batch_size = 500; // Lines to be read per batch
$batch = 0;
$counter = 0;
$lines = 0;

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Remove Existing Data from table
$sql = "TRUNCATE TABLE  `workorderstest`";
$conn->query($sql);

$handle = fopen(dirname(__FILE__)."/files/workorders.csv" , "r");

//instead of executing query one by one,
//let us prepare 1 SQL query that will insert all values from the batch

$sql_prefix ="INSERT INTO workorderstest(id,parentid,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10) VALUES ";
$values = "";

while (($line = fgets($handle)) !== false) {
    $values .= "($line),";
    $counter++;
    $lines++;
    if ($counter == $batch_size) {
        $values = substr($values, 0, strlen($values) - 1);
        $conn->query($sql_prefix . $values) or die($conn->error);
        $counter = 0;
        $values ="";
        $batch++;
    }
}
if ($counter > 0) { // Execute the last batch
    $values = substr($values, 0, strlen($values) - 1);
    $conn->query($sql_prefix . $values) or die($conn->error);
}

// Output results
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Importing Script running at: $date <br/>";
echo "Timezone: $timezone <br/>";
echo "<br/>";
echo "Script Summary:";
echo "Time running script: " . round($time,3) . " seconds <br/>";
echo "Memory: ".memory_get_usage() . " bytes <br/>";
echo "Records Updated: $lines <br/>";
echo "Batches run: $batch <br/>";

?>
4

2 回答 2

1
  1. fgets()最好用这个吗?这是一个很好的方法。另一种选择是用 将整个文件读入一个数组file(),然后用 循环遍历数组foreach()

  2. 我需要加入回调吗?不,只需在从文件中读取每批行后执行查询。

  3. 从哪儿开始?当计数器达到批量大小时,执行查询。然后将计数器设置回0并将查询字符串设置回初始值。最后,在循环结束时,您需要使用剩余值执行查询(除非文件大小是批处理大小的精确倍数,在这种情况下不会有任何剩余)。

$batch_size = 100;
$counter = 0;

//instead of executing query one by one,
//let us prepare 1 SQL query that will insert all values from the batch

$sql_prefix ="INSERT INTO workorderstest(id,parentid,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10) VALUES ";
$values = "";

while (($line = fgets($handle)) !== false) {
    $values .= "($line),";
    $counter++;
    if ($counter == $batch_size) {
        $values = substr($values, 0, strlen($values) - 1);
        $conn->query($sql_prefix . $values) or die($conn->error);
        $counter = 0;
        $values ="";
    }
}
if ($counter > 0) { // Execute the last batch
    $values = substr($values, 0, strlen($values) - 1);
    $conn->query($sql_prefix . $values) or die($conn->error);
}
于 2016-12-23T02:41:59.540 回答
1

这是对车轮的重新发明。mysql 有一个非常快速和高效的系统来将 CSV 数据加载到表中。这就是LOAD DATA INFILE如果您对您的用户帐户具有正确的权限,您可以从 PHP 内部调用代码。并且 LOAD DATA 内置了对跳过 N 行的支持。

$path = dirname(__FILE__)."/files/workorderstest.csv";
$q = "LOAD DATA INFILE ? INTO TABLE workorderstest IGNORE ? LINES";
$stmt = $dbh->prepare($q);
$stmt->bindParam(1,"$dirname");
$stmt->bindParam(2,"$n");
$stmt->execute();

那是宝贵的几行代码,不是吗?

请注意,此代码使用 IGNORE LINES 关键字跳过 CSV 中的行。您也可以使用 IGNORE 关键字,例如

LOAD DATA INFILE ? IGNORE INTO TABLE ....
于 2016-12-23T02:43:01.430 回答