插入/更新每一行时导出MySQL表,将其标记为"导出"或同等学历

时间:2016-11-01 21:18:52

标签: php mysql csv

我可以使用PHPMyAdmin或我当前的PHP脚本使用Cron作业将我的表导出到csv文件就好了,但是我试图将它移到无法再次导出这些行的地方。我的想法是只更新或在列中插入一个值,将其标记为"导出"并尝试找到一种方法来只导出未标记为这样的行。这是我的导出PHP脚本,如果它有帮助。感谢

<?php
 // mysql database connection details
    $host = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "database";

    // open connection to mysql database
    $connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));

    // fetch mysql table rows
    $sql = "select * from product_sheets";
    $result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection));

$csv_fields=array();  // header array for the csv file

$csv_fields[]='header1';
$csv_fields[]='header2';


    $fp = fopen('/home/blog2696/public_html/productsheet/Exports/export.csv', 'w');

        fputcsv($fp, $csv_fields);

    while($row = mysqli_fetch_assoc($result))
    {
        fputcsv($fp, $row);
    }

    fclose($fp);

    //close the db connection
    mysqli_close($connection);
?>

1 个答案:

答案 0 :(得分:1)

首先,将名为“exported”的布尔字段添加到表中,默认值为FALSE(0)。

其次,将SELECT更改为仅选择导出为false的记录。

$sql = "select * from product_sheets where exported = 0";

第三,在将CSV写入后,将记录的“导出”字段更新为TRUE(1)。

$export_mark_sql = "UPDATE product_sheets SET exported = 1 WHERE primary_key= " . $row['primary_key'];
$export_mark_result = mysqli_query($connection, $export_mark_sql ) or die("Update Error " . mysqli_error($connection));

现在一起:

<?php

// mysql database connection details
$host = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

// open connection to mysql database
$connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));

// fetch mysql table rows for all records that haven't been exported already
$sql = "select * from product_sheets where exported = 0";
$result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection));

$csv_fields=array();


$fp = fopen('/home/blog2696/public_html/productsheet/Exports/export.csv', 'w');

    fputcsv($fp, $csv_fields);

while($row = mysqli_fetch_assoc($result))
{
    // Mark this exported record as exported=true
    // -- Change "primary_key" below to the primary key field of the "product_sheets" table.
    $export_mark_sql = "UPDATE product_sheets SET exported = 1 WHERE primary_key= " . $row['primary_key'];
    $export_mark_result = mysqli_query($connection, $export_mark_sql ) or die("Update Error " . mysqli_error($connection));
    fputcsv($fp, $row);
}

fclose($fp);

//close the db connection
mysqli_close($connection);
?>