Reputation: 3857
I am having a small programming issue. I am trying to execute a function within a class and I have an array that I am using array_walk to execute a function on each variable within that array. The issue is that the function I am executing is a method within the same class. I have looked over my code however cannot find what the issue is. Please let me know what a possible solution to this error is or if you see something I am not seeing.
Currently it is not even executing the function escape()
. I purposely added a ' in the status variable as I want it to be escaped, but it is done not.
A little background: This is a database class I am building and the prepare()
method will help escape variables in the query before it is executed. I removed some code that is not relevant to this issue.
This is the result it is giving me: UPDATE table_name SET status='I'm doing good!' WHERE username='someone'
<?php
class Database {
var $weak_escape = false;
function escape($str) {
if ($this->weak_escape) return $this->weak_escape($str);
else return $this->sql_escape($str);
}
function weak_escape($str) {
return addslashes($str);
}
function sql_escape($str) {
return mysql_real_escape_string($str);
}
function prepare($query) {
$args = func_get_args();
array_shift($args);
array_walk($args, array(&$this, 'escape'));
return vsprintf($query, $args);
}
}
$db = new Database();
$username = "someone";
$status = "I'm doing good!";
echo $db->prepare("UPDATE table_name SET status='%s' WHERE username='%s'", $status, $username);
?>
Upvotes: 3
Views: 3669
Reputation: 3123
Hope this is what you are looking for. I did this:
class Database {
function escape($str) {
return addslashes($str);
}
function prepare($query) {
$args = func_get_args();
$args[1] = $this->escape($args[1]);
array_shift($args);
array_walk($args, array($this, 'escape'));
return vsprintf($query, $args);
}
}
$db = new Database();
$username = "someone";
$status = "I'm doing good!";
print $db->prepare("UPDATE table_name SET status='%s' WHERE username='%s'", $status, $username);
got result:
UPDATE table_name SET status='I\'m doing good!' WHERE username='someone'
Upvotes: 1
Reputation: 117334
You'll need to modify the argument(reference of array-item), this isn't done if you return it:
function escape(&$str)
{
$str=addslashes($str);
}
Upvotes: 1
Reputation: 18354
I'de make my escape function static, cause it's the same for every instance:
class Database {
static function escape($str) {
return addslashes($str);
}
function prepare($query) {
$args = func_get_args();
array_shift($args);
array_walk($args, array('Database', 'escape')); //Look here
return vsprintf($query, $args);
}
}
Hope this helps. Cheers
Upvotes: 2