Creating a PHP PDO database class, trouble with the OOP -


this current database class:

class database {      private $db;      function connect() {         $db_host = "localhost";         $db_name = "database1";         $db_user = "root";         $db_pass = "root";         try {             $this->db = new pdo("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_user, $db_pass);         } catch(pdoexception $e) {             die($e);         }     }      public function getcolumn($tablename, $unknowncolumnname, $columnonename, $columnonevalue, $columntwoname = "1", $columntwovalue = "1") {         $stmt = $this->db->query("select $tablename $unknowncolumnname $columnonename='$columnonevalue' , $columntwoname='$columntwovalue'");         $results = $stmt->fetchall(pdo::fetch_assoc);         return $results[0][$unknowncolumnname];     } } 

i'm trying run using following code:

$db = new database(); $db->connect(); echo $db->getcolumn("sessions", "token", "uid", 1); 

and following error:

php fatal error: call member function fetchall() on non-object in /users/retracted/retracted/root/includes/database.php on line 19

any idea what's up? thanks

  1. this function prone sql injection.
  2. this function won't let column using simplest or condition.
  3. this function makes unreadable gibberish out of natural english of sql language.

look, spoiled writing function. how suppose used every day coding? matter of fact, function makes experience harder raw pdo - have learn new syntax, numerous exceptions , last-minute corrections.

please, turn raw pdo!

let me show right way

public function getcolumn($sql, $params) {     $stmt = $this->db->prepare($sql);     $stmt->execute($params);     return $stmt->fetchcolumn(); } 

used this

echo $db->getcolumn("select token sessions uid = ?", array(1)); 

this way you'll able use full power of sql not limited silly subset, security of prepared statements, yet keep code comprehensible.
while calling still in 1 line - initial (and extremely proper!) intention.


Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -