我想用mysqldump备份一个表的最后记录


I want to backup last records of a table with mysqldump

目前我有这个:

exec('mysqldump --user=$DBUSER --password=$DBPASSWD --host= localhost DB_NAME (select column from database.table where= column > 1234) > table.sql');

当然,当我在服务器上使用浏览器打开文件时,什么也不会发生。现在,下一段代码确实输出了一个SQL文件,但是是一个空文件:

set_time_limit(600);
system("mysqldump -h localhost -u $DBUSER -p $DBPASSWD $DATABASE  > table.sql");

我要保存每天生成的记录,以便以后可以进行增量备份。

为什么system()输出文件而exec()没有?

如果您的目标是对数据库进行增量备份,那么mysqldump不是理想的选择。

这里你可以做两件事:

  1. [BAD WAY]使用PHP代码序列化和转储CSV和JSON格式的新记录,并使用它

  2. 你可能想在MySQL中使用binlog,这将帮助你做到这一点(点击链接阅读MySQL备份方法)

转储选择记录:

$recset = mysql_query("select column from database.table where= column > 1234");
for($recset as $row){
    file_put_contents("filename.json", json_encode($row) . "'n")
}

现在,一旦需要,您可以一行一行地阅读此文件,并使用json_enocode在php数组/对象中获取您的数据,并按照您的意愿使用它。

[Edit: After looking After your pastebin code]

根据需要修改一些变量名和代码后。

$docsql='nts.sql';
require("cnxn.php");
error_reporting(E_ALL);
ini_set('display_errors', '1');
$q1=mysqli_query($cnx,"SELECT * FROM table WHERE col > '45678' ORDER BY col ASC");
$data_records=array();
while($r1=mysqli_fetch_assoc($q1)){
    $cntn=htmlentities($r1['cntn']);
    array_push($data_records, "(".$r1['col1'].",'".$r1['col2']."','".$r1['col3']."','".$r1['col4']."','".$r1['col5']."')");
}
$insert="INSERT INTO notas (col1, col2, col3, col4, col5) VALUES ";
file_put_contents($docsql, $insert);
foreach($data_records as $record){
    file_put_contents($docsql, $record) . "'n", FILE_APPEND);
}

对于akm建议的解决方案,我只是添加了最后一笔,将最后一个逗号替换为分号:

$docsql='nts.sql';
require("cnxn.php");
error_reporting(E_ALL);
ini_set('display_errors', '1');
$q1=mysqli_query($cnx,"SELECT * FROM table WHERE col > '45678' ORDER BY col  ASC");
$data_records=array();
while($r1=mysqli_fetch_assoc($q1)){
$cntn=htmlentities($r1['cntn']);
array_push($data_records, "(".$r1['col1'].",'".$r1['col2']."','".$r1['col3']."','".$r1['col4']."','".$r1['c ol5']."')");
}
$insert="INSERT INTO notas (col1, col2, col3, col4, col5) VALUES ";
file_put_contents($docsql, $insert);
foreach($data_records as $record){
    file_put_contents($docsql, $record) . "'n", FILE_APPEND);
}
$chng = fopen("nts.sql", "a+") or die("cant open file");
$rmv = fstat($chng);
ftruncate($chng, $rmv['size']-2);
fwrite($chng,';');
fclose($chng);

那工作做得很好。谢谢你,Rock.