Using an array in a class

I have a problem with a little programming. I am trying to execute a function inside a class, and I have an array that I use array_walk to execute a function for every variable in this array. The problem is that the function I perform is a method inside the same class. I looked through my code, but I can not find what the problem is. Please let me know what a possible solution to this error is or you see something that I do not see.

Currently, it does not even perform a function escape(). I intentionally added 'to the status variable as I want it to be escaped, but this is not done.

A bit of background: this is the database class that I am creating, and the method prepare()will help to avoid variables in the query before executing it. I removed code that is not related to this problem.

This is the result he gives 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);
?>
+3
source share
3 answers

You will need to change the argument (reference to the array element), this will not be done if you return it:

function escape(&$str)
{
  $str=addslashes($str);
}
+1
source

I'de make my escape function static, make it 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. Greetings

+2
source

Hope this is what you are looking for. I have done 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 the result:

UPDATE table_name SET status='I\'m doing good!' WHERE username='someone'
+1
source

All Articles