如何从 WHERE 子句导出 MySQL 表的某些行?

问题描述:

如何使用 PHP 脚本中的 where 子句导出 MySQL 表的某些行?

How to export some rows of a MySQL table with where clause from a PHP script?

我有一个 MySQL 说 test,我想使用 PHP 脚本为 id 在 10 到 100 之间的行创建一个可导入的 .sql 文件.

I have a MySQL say test and I want to create a importable .sql file for rows where id are between 10 and 100, using PHP script.

我想创建一个可以导入 MySQL 数据库的 sql 文件 test.sql.

I want to create a sql file say test.sql which can be imported to MySQL database.

我的代码:

$con=mysqli_connect("localhost", "root","","mydatabase");

$tableName  = 'test';
$backupFile = '/opt/lampp/htdocs/practices/phpTest/test.sql';
$query      = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName WHERE id BETWEEN 10 AND 500";

$result = mysqli_query($con,$query);

这会创建一个 test.sql 文件,但是当我尝试导入时,它给出了错误 #1064.
我的脚本只创建一个文件,其中包含列名和表结构或插入查询的行.

This creates a test.sql file, but when I try to import, it gives error #1064.
My script only creates a file with rows with columns name and table sturcute or insert query.

如评论中所述,您可以通过以下方式使用 mysqldump.

As mentioned in the comments you can use mysqldump the following way.

mysqldump --user=... --password=... --host=... DB_NAME --where=<YOUR CLAUSE> > /path/to/output/file.sql

如果你想让它在你的php文件中,你可以执行以下操作

If you want this to be in your php file you can do the following

exec('mysqldump --user=... --password=... --host=... DB_NAME --where=<YOUR CLAUSE> > /path/to/output/file.sql');