错误:PHP exec期间未终止的引用字符串

时间:2015-08-14 07:29:16

标签: php mysql bash

我在PHP中使用exec函数使mysql将查询内容转储到CSV文件中。

这是我的代码:

$outfile = '/home/dotslash/file.csv';
$emails_table = 'all_emails';

$host = 'localhost';
$user = 'root';
$pass = 'root';
$dbname = 'test';

$query = "SELECT DISTINCT(emailid), COUNT(emailid), GROUP_CONCAT(DISTINCT offers) FROM '" . $emails_table . "' GROUP BY emailid INTO OUTFILE '" . $outfile . "' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n';";

exec("mysql -h$host -u$user -p$pass $dbname -e '$query'");

我收到此错误:sh: 2: Syntax error: Unterminated quoted string

我知道当字符串从PHP传递给bash时问题就是逃避,但我无法弄清楚我做错了什么。请帮忙!

2 个答案:

答案 0 :(得分:1)

您是否已连接到数据库?在你的脚本中它似乎没有......在你的数据库信息之后添加这个字符串:

$con = mysql_connect($host, $user, $pass);
mysql_select_db($dbname);

在脚本的末尾添加:

mysql_close($con);

所以你的代码看起来像是:

  $outfile = '/home/dotslash/file.csv';
$emails_table = 'all_emails';

$host = 'localhost';
$user = 'root';
$pass = 'root';
$dbname = 'test';

$con = mysql_connect($host, $user, $pass);
    mysql_select_db($dbname);

$query = "SELECT DISTINCT(emailid), COUNT(emailid), GROUP_CONCAT(DISTINCT offers) FROM '" . $emails_table . "' GROUP BY emailid INTO OUTFILE '" . $outfile . "' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n';";

exec("mysql -h$host -u$user -p$pass $dbname -e '$query'");

mysql_close($con);

使用

的SQL可能存在问题
   ... ENCLOSED BY '\"' ...

尝试将其替换为:

$enc = '"';

... ENCLOSED BY '".$enc."' ...

所以你的最终代码是:

$outfile = '/home/dotslash/file.csv';
    $emails_table = 'all_emails';

    $host = 'localhost';
    $user = 'root';
    $pass = 'root';
    $dbname = 'test';

    $con = mysql_connect($host, $user, $pass);
        mysql_select_db($dbname);

$enc = '"';

    $query = "SELECT DISTINCT(emailid), COUNT(emailid), GROUP_CONCAT(DISTINCT offers) FROM '" . $emails_table . "' GROUP BY emailid INTO OUTFILE '" . $outfile . "' FIELDS TERMINATED BY ',' ENCLOSED BY '".$enc."' LINES TERMINATED BY '\n';";

    exec("mysql -h$host -u$user -p$pass $dbname -e '$query'");

mysql_close($con);

如果这不能解决您的问题,请尝试使用连接来传递$ query var,如下所示:

exec("mysql -h$host -u$user -p$pass $dbname -e ".$query."");

还尝试var_dump你的$ query这样:

var_dump($query);

因为您可能需要在将结果传递给exec命令之前获取结果。

Pro-Tip:检查您的SQL命令是否正确,直接从phpmyadmin上的数据库传递命令,并检查是否有错误。

答案 1 :(得分:0)

执行$ query的var_dump,然后在phpmyadmin或其他sqlmanager的sql控制台中将var_dump返回的字符串放入后查看结果。

我的英语是法语