0

I have this PHP:

exec("/csvexport.sh $table");

Which runs this bash script (it exports a table to 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

This works fine. However I want the query to be dynamic like so:

$query = "SELECT field1, field2, IF(field3 = '0000-00-00','0001-01-01',field3) AS field3 FROM mytable;";
exec("/csvexport.sh $query $table");

If I change my bash like so:

#!/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

Even though everything is "identical" it gives the following error:

sh: -c: line 0: syntax error near unexpected token `('

So I'm thinking it isn't happy with how the query contains brackets when passed from PHP?

2
  • 1
    It may be easier to create a php-cli script. PHP contains all the functions for MySQL, mysqli and can handle cli parameters.
    – jc__
    Jun 18, 2018 at 18:03
  • Precisely! Why scratching your left ear with the right hand? Shelling out bears many risks, which can be eliminated by letting PHP do all the work.
    – ajeh
    Jun 18, 2018 at 18:34

2 Answers 2

1

Passing parameters to a shell script from PHP.

Its all about the "strings", and when to "double quote" for expansion.

<?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";

?>

BTW: I did not test this snippet.

0

I'm not a PHP guy, but it seems you'll need to do something like

exec(escapeshellcmd("/csvexport.sh \"$query\" $table"));

Does PHP have a function where you can call the command and pass the arguments separately?

some_exec_function("/csvexport.sh", $query, $table);  # ???

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .