Skip to content
Advertisement

Use of Complex (curly) Syntax in external file

I am having a problem with getting an sql query to interpolate as I would want, and would be grateful for some help please.

Within the manual page for pg_query_params,there is a code example for pg_query() passing a variable using curly braces. This appeared to be exactly what I need for my task. So, my code is as follows:

$fh = fopen('/home/www/KPI-Summary.sql',"r")
      or die("Problem opening SQL file.n");
$dbh = pg_connect("$connect")
      or die('Could not connect: ' . pg_last_error());
$j = 0;
while (($line = fgets($fh)) !== false) {
    $tmp[$j] = array();                         // Initialise temporary storage.
    $result = pg_query($dbh, $line);            // process the line read.
    if (!$result) { echo "Error: query did not execute"; }
...
    while ($row = pg_fetch_row($result)) {      // Read sql result.
        $tmp[$j][2][] = $row;
        }
    $j++;
    }
fclose($fh);

The sql file contains several queries, one per line, like this:

SELECT count(*) from table WHERE value=0 AND msgid='{$arg[1]}';

However, currently, my variable is not being replaced by the contents — and therefore although the query runs OK, it is returning zero rows. What do I need to do in order to get the expected result? (Note: each sql line varies, and the query parameters are not constant — hence using variable(s) within the sql file.)

Advertisement

Answer

OK. I have a solution (although it might not be the correct approach). This works — but it needs polish I think. Suggestions regarding a better regexp would be very much appreciated.

$bar = 'VALUE-A';         // Can we replace simple variable names?
$arg[1] = 'VALUE-B';      // What about an array, such as $arg[1]?

function interpolate($matches){
        global $bar;
        global $arg;
        if ($matches[2]) {
                $i = isset(${$matches[1]}[$matches[2]]) ? ${$matches[1]}[$matches[2]] : 'UNDEF';
                } else {
                $i = isset(${$matches[1]}) ? ${$matches[1]} : 'UNDEF';
                }
        return $i;
        }

$fh = fopen('/home/www/file.sql',"r") or die("Failed.n");
while (($line = fgets($fh)) !== false) {
...
        $line = preg_replace_callback('|{$([a-z]+)[*(d*)]*}|i', "interpolate", $line);
        echo $line;       // and continue with rest of code as above.
        }
fclose($fh);

(Of course, the solution suggests that the question title is completely wrong. Is there any way to edit this?)

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement