2

I searched before posting this but didn't find an answer to my question.

I have a table in a database which stores queries such as (with the php variable stored in the database):

select * from accounts where type = 'client'
select * from accounts where user_id = $userid
select * from accounts where name = '$name'

I assumed that when I pulled that particular query from the database that PHP would recognized the variable and replace it but it treats it as regular text.

Is there a way to have PHP replace the $__ with an actual variable that exists? I think maybe the eval() function perhaps??

DeltaTango
  • 821
  • 2
  • 9
  • 19
  • from where did you execute the script? for php variable to work you should execute your sql statement within the php script – Ibrahim Azhar Armar Apr 24 '12 at 17:12
  • Similar question: http://stackoverflow.com/questions/283222/best-way-to-substitute-variables-in-plain-text-using-php – Trevor Apr 24 '12 at 17:13

3 Answers3

1

What you might try is using it as a prepared statement. So instead, if your database stored queries looked like this:

select * from accounts where type = 'client'
select * from accounts where user_id = ?
select * from accounts where name = ?

and you use PDO prepared statements like this:

$pdo = new PDO($dsn, $user, $pass);
$statement = $pdo->prepare($secondOfTheAboveQueries);
$statement->execute(array($userId));
$account = $statement->fetch();

You could also use prepared queries with named variables like user_id = :userid instead of questions marks if you have to process a few statements at a time with various variables.

You may also want to consider stored procedures which work similarly. An explanation for both can be found here:

http://php.net/manual/en/pdo.prepared-statements.php

dqhendricks
  • 19,030
  • 11
  • 50
  • 83
0

Assuming that you pull the query from a database:

$string = ''; // Assign the real userID

while ($fetch = mysql_fetch_array($query)) {

    $newQuery = str_replace('$userid', $string, $fetch['your_row_name']); 
} 

I'm not sure if this will work, but this is what i would try first...

Adriaan
  • 376
  • 1
  • 6
  • 21
0

sprint seems to work well. instead of storing them as $variable, I can use %s, etc.

DeltaTango
  • 821
  • 2
  • 9
  • 19