php - class array within double quotes -


i have follow 2 classes

class   {          ....   protected  $arr = array('game_id','pl_id');   ...   }    class b extends    {       //for example here add method       private function add_to_db()       {          $query = "insert table(game_id,player_id)                          values(????,????)";   //here question,what must write?? mysql_query($query); }   } 

i try write ..values(\"$this->arr[game_id]\",\"$this->arr[pl_id]\")", or
values(".$this->arr[game_id].",".$this->arr[pl_id].")" ,but not working.

thanks advise

i think found solution of question. in class must have _set , _ methods.
class a
{
....
protected arr = array('game_id'=>null,'pl_id'=>null);

    function __set($property, $value)    {        if (array_key_exists($property, $this->arr)) {            $this->arr[$property] = $value;        } else {            print "error: can't write property other x & y\n";        }  }     function __get($property)   {       if (array_key_exists($property, $this->arr)) {            return $this->arr[$property];       } else {           print "error: write correct property";       }   }  ...   }   

and after in class b can write follow

private function add_to_db()
{
$query = "insert table(game_id,player_id)
values(\"$this->game_id\",\"$this->pl_id\")"; //here question
mysql_query($query);
}

thanks advise

the best solution use pdo_mysql prepare , execute queries parameters. wouldn't have worry quotes @ all. it's simple this:

$stmt = $pdo->prepare("insert table (game_id, player_id)                         values (:game_id, :pl_id)"); $stmt->execute($this->arr); 

the plain mysql extension php doesn't support parameters in sql queries. if must continue use api, should @ least use technique protect against sql injection. example, if they're integers, coercion int:

$g = (int) $this->arr["game_id"]; $p = (int) $this->arr["pl_id"]; $query = "insert table(game_id,player_id) values({$g}, {$p})"; mysql_query($query); 

if they're strings, must escape values using provided function:

$g = mysql_real_escape_string($this->arr["game_id"]); $p = mysql_real_escape_string($this->arr["pl_id"]); $query = "insert table(game_id,player_id) values('{$g}', '{$p}')"; mysql_query($query); 

also remember quote array keys or else they'll interpreted php constants, not strings.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -