I have created a simple database abstraction layer for an application I am working on. In order to deal with differences in SQL syntax between database servers, I have decided to aggregate all of my queries together (this also supports code reuse)--see this thread for more info. However, I'm running into two problems. Basically, I need to store a variable name within an array and then have that variable expanded later. Here's some simplified code to illustrate:
PHP Code:class DB{
function execute_query($query){
#Pretend all the code to run a query is here...
}
function queries(){
$queries = array(
0 => "SELECT * FROM users WHERE username='$username'",
1 => "Some other query",
);
return $queries;
}
}
class Something{
function get_user($username){
$DB = new DB;
$queries = $DB->queires();
$result = $DB->execute_query($queries[0]);
return $result;
}
}
$Cheetohs = new Something;
$username = "Chester";
$user_data = $Cheetohs->get_user($username);
The two problems I am running into are:
(1) php tries to expand the variable $username before storing it as part of the string in the array. I need it to be stored as '$username' in the array and I have no idea how to prevent php from trying to expand it. In the example above, PHP would throw an error saying that $username was undefined.
(2) Assuming that the first problem is addressed, then $username within $queries[0] isn't expanded when $queries[0] is included as an argument for my query function. Instead of passing this string to my DB server: "SELECT * FROM users WHERE username='Chester'", it would pass "SELECT * FROM users WHERE username='$username'". I think writing like this may fix that problem:
But I haven't been able to test it because of the first issue.PHP Code:$result = execute_query(eval($queries[0]));
So, what do you think? Is this just not going to work at all? Any ideas for how I can achieve this? THANKS!


The two problems I am running into are:

Thanks Logic_Earth, that worked perfectly. Now I can be on to troubleshooting problem #2 with using eval() to try and expand the variable within the array...

Bookmarks