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

2

3 Answers 3

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

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...

1
  • i just realized probably using sprintf might do the job as well
    – DeltaTango
    May 8, 2012 at 13:01
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.