Reputation: 1607
I am having a variable $query1
and in this, I have a query string and in this query string, I have used another variable $sORp
. The main problem is that I want to give this $sORp
variable a value at runtime without changing my string variable holding the query. Is this possible?
Code Snippet is as below(dummy example):
$query1="SELECT $sORP,name from table1
where $sORp=:SRC_NAME
group by $sORp,name
order by $sORp";
I want to assign this variable $sORp
"SRC" and "POOL" at run time as I don't want to write query twice with different values.
Use in code:
$sORp='SRC';
$sql=$query1;
$sth = oci_parse($con,$sql);
And this is not working, Is there any solution for this.
And on running this PHP file the error is: ORA-00936: missing expression
Upvotes: 2
Views: 93
Reputation: 77063
No, it's not possible. When a string is evaluated, then its value is determined, even if you used a variable to do that and the variable later changes. You try to optimize the way you generate the string, but you prematurely optimize. The string generation will be quick in your case, at least in comparison to your query. You could minimalize the number of queries generated this way:
$cachedQueryTexts = array();
function generateQueryText($key) {
return (isset($cachedQueryTexts[$key])) ? $cachedQueryTexts[$key] : ($cachedQueryTexts[$key] = "your query using the $key variable");
}
Upvotes: 1
Reputation: 8393
You cannot do this in this scripting language. $sql
must be defined after $sORp
.
$sORp='SRC';
$sth = oci_parse($con,"SELECT $sORP,name from table1
where $sORp=:SRC_NAME
group by $sORp,name
order by $sORp");
If you want your can create a function which will generate the right query on will:;
function foo($sORp) {
$retVal="SELECT $sORP,name from table1
where $sORp=:SRC_NAME
group by $sORp,name
order by $sORp";
return $retVal;
}
$sth = oci_parse($con,foo($sORp));
Upvotes: 1
Reputation: 94682
Assign a value to the variable before using it in string literal. Double quoted string literals will then automatically expand the variables used inside the double quoted string literal.
$sORp='SRC';
$query1="SELECT $sORP,name from table1
where $sORp=:SRC_NAME
group by $sORp,name
order by $sORp";
echo $query1;
// run query
$sORp='POOL';
$query1="SELECT $sORP,name from table1
where $sORp=:SRC_NAME
group by $sORp,name
order by $sORp";
echo $query1;
Upvotes: 1