我有这个 PHP:
exec("/csvexport.sh $table");
它运行这个 bash 脚本(它将表导出到 CSV):
#!/bin/bash
table=$1
mysql --database=db --user=user --password=pass -B -e "SELECT field1, field2, IF(field3 = '0000-00-00','0001-01-01',field3) AS field3 FROM mytable;" | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > /home/backups/$table.csv
这很好用。不过我希望查询是动态的,如下所示:
$query = "SELECT field1, field2, IF(field3 = '0000-00-00','0001-01-01',field3) AS field3 FROM mytable;";
exec("/csvexport.sh $query $table");
如果我像这样改变我的 bash:
#!/bin/bash
query=$1
table=$2
mysql --database=db --user=user --password=pass -B -e "$query" | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > /home/backups/$table.csv
即使一切都是“相同的”,它也会给出以下错误:
sh: -c: line 0: syntax error near unexpected token `('
所以我想它对从 PHP 传递的查询包含括号的方式不满意?
答案1
从 PHP 向 shell 脚本传递参数。
一切都与“字符串”以及何时使用“双引号”进行扩展有关。
<?php
/* exec("/csvexport.sh $table"); */
/* double quote here because you want PHP to expand $table */
/* Escape double quotes so they are passed to the shell because you do not wnat the shell to choke on spaces */
$command_with_parameters = "/path/csvexport.sh \"${table}\"";
$output_from_command = "";
$command_success = "";
/* double quote here because you want PHP to expand $command_with_parameters, a string */
exec("${command_with_parameters}", $output_from_command, $command_success);
/* or to keep it simple */
exec("/path/csvexport.sh \"${table}\"");
/* show me what you got */
echo"${command_success}\n${output_from_command}\n";
?>
顺便说一句:我没有测试这个片段。
答案2
我不是 PHP 人员,但似乎你需要做类似的事情
exec(escapeshellcmd("/csvexport.sh \"$query\" $table"));
PHP 是否有一个函数可以单独调用命令并传递参数?
some_exec_function("/csvexport.sh", $query, $table); # ???