我的服务器中存储了 email.txt,email.txt 的路径是
/home/xxxx/public_htnl/email.txt
email.txt 包含数千封每天更新的订阅者电子邮件。 我想每天使用 cron 将这些电子邮件导入其他数据库。
我试过了,但是报错
无法加载。 用户 'test'@'localhost' 的访问被拒绝(使用密码:YES)
我想我没有权限运行 LOAD DATA INFILE
我的代码是:
<?php
$db = mysql_connect('localhost', 'test', 'test')
or die('Failed to connect');
mysql_select_db('test', $db);
$string = file_get_contents("http://www.xyz.com/email.txt", "r");
$myFile = "/home/xxx/public_html/email.txt";
$fh = fopen($myFile, 'w') or die("Could not open: " . mysql_error());
fwrite($fh, $string);
fclose($fh);
$result = mysql_query("LOAD DATA INFILE '$myFile'" .
" INTO TABLE email");
if (!$result) {
die("Could not load. " . mysql_error());
}
?>
任何其他好的方法都可以接受。请不要建议在存储电子邮件等时直接将数据存储在其他数据库中。
最佳答案
作为 root MySQL 用户,尝试运行查询:
GRANT FILE on *.* to 'test'@'localhost';
如果仍然出现错误,请确保测试用户的用户名和密码正确,并且您访问 MySQL 的主机与测试用户和密码的主机相匹配。
编辑:
<?php
$db = mysql_connect('localhost', 'test', 'test') or die(mysql_error());
if (!mysql_select_db('test', $db)) die(mysql_error());
$emails = file("http://www.xyz.com/email.txt");
foreach($emails as $email) {
$email = trim($email);
if ($email == '' || strpos($email, '@') === false) continue;
$email = mysql_real_escape_string($email);
$query = "INSERT INTO `email` VALUES('$email')";
$result = mysql_query($query);
if (!$result) {
echo "Failed to insert $email. " . mysql_error() . "<br />\n";
}
}
如果有很多很多电子邮件,您可以构建一个电子邮件地址数组并每隔一段时间进行一次扩展插入。
INSERT INTO emails VALUES('email1'), ('email2'), ('email3'), ('email4')
关于php - 将文本文件每行上传到 mysql 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11910861/