I kind of figured it was only being seen as a string, and I've thought of
a few ways around it (explode() and implode() being the most likely
candidates at present). I was just hoping that I had overlooked
something, and that some complexity could be engineered out.
On Tue, 23 Mar 2004, Jeffrey Silverman wrote:
[color=blue]
> On Tue, 23 Mar 2004 11:33:16 -0600, bofh wrote:
>[color=green]
> > I'm working on a project where I need to store a CGI query in a
> > database field. The query contains variables which will be substitued
> > at runtime (e.g., today's date, key to select upon, etc), and may be
> > pointed to different URLs depending upon the table key.
> >
> > The variable substitution works fine when hardcoding into the script,
> > e.g.:
> >
> >
> > $var1='data1';
> > $var2='data2';
> > $a="http://www.webserver.com/query.cgi?a=$var1&b=$var2";
> > $fd=fopen($a,"r");
> > ...
> >
> > However, the substitution fails when the query is pulled from a database
> > record, e.g.
> >
> > //Only one record returned for testing purposes.
> > //
> > //location field (varchar) is:
> > //"http://www.webserver.com/query.cgi?a=$var1&b=$var2"
> >
> > $var1='data1';
> > $var2='data2';
> > $dbconn=yadda yada;
> > $dbquery=pg_query($dbconn,"select key,location from schema.table");
> > $row=pg_fetch_assoc($dbquery);
> > $fd=fopen($row['location'],"r");
> > ...
> >
> > In this case, the variable substitution doesn't occur in the query (i.e.,
> > $var1 remains the string $var1, instead of changing into the value of say,
> > '03-23-2004'). I've tried different variations, and treating as a
> > variable variable (with $$row['url'] and ${$row['url']}. No joy.
> >
> > Any ideas would be appreciated. Thanks.[/color]
>
>
> It's not working because the SQL result set is just a string that has no
> relation whatsoever to the variables $var1 and $var2. I.e. the string is
> not treated as PHP.
>
> You could use eval().
>
> Or you could use a regex replace. example:
>
> preg_replace("/$var1/", $var1, $row['location']);
> (...repeat for $var2...)
>
> Or, if the query string is always going to include "a=$var1" and "b=$var2"
> you could recreate the query string from scratch:
>
> (assuming $row['location'] contains only the URL without the query
> string):
>
> $url = $row['location'] . "?a=$var1&b=$var2";
>
> There are probably other ways to solve this problem, as there are always
> at least two more ways to do something beyond even the half dozen you may
> have thought of. good luck...
>
> --
> Jeffrey D. Silverman | jeffrey AT jhu DOT edu
> Website |
http://www.wse.jhu.edu/newtnotes/
>
>[/color]
-------------------------------------------------
Only in America will someone |
order a Big Mac, large fries, |
bofh@visi.com
and a *Diet* Coke... |