Where can I find a good tutorial on how to make a multi-use database class using php and mysql? -
i've been trying hours make 1 class file handle database work (statements, security (sql injection prevent), etc) won't have keep writing statements update or insert every time need one. there tutorials online show how create multi-purpose database class prepared statements?
he class tried construct brain killing me. :s
<?php $d = new database(); // test class database { protected $db_connect; protected $statement; function database() { try { $this->db = new pdo("mysql:host=localhost;dbname=test", "root", "") or die("could not connect server."); } catch (pdoexception $e) { echo $e->getmessage(); } try { $this->preparedquery("insert feedback (name, feedback) values (?, ?)", array("this name", "this feedback w00t feedback")); } catch (invalidargumentexception $e) { echo $e->getmessage(); } } protected function cleanparameter($strline) { $strcleansedline = preg_replace("/[^a-za-z0-9\s]/", "", $strline); return $strcleansedline; } public function preparedquery($strquery, $parameters = null, $types = null) { try { $query = $this->db->prepare($strquery); if ($this->startswith(strtolower($strquery), "select")) { echo "no"; } else { // insert, update, delete here. $params; ($i = 0; $i < count($parameters); $i++) { $parameters[$i] = $this->cleanparameter($parameters[$i]); $params = array($i => $parameters[$i]); $query->bindvalue(do($i), $params[$i]); // still won't work //echo $params[$i]."<br />"; } // maybe work? foreach($params $key => $value) { //$d = explode("\ ", $value); echo $params[$key]."------------------"; //echo $key."<br />".$value." -----------------"; $query->bindvalue($key, $value); } } //$this->statement->bind_param("ss", $name, $feedback); //$query->execute(); $this->close(); echo "done!"; } catch(exception $e) { echo $e->getmessage(); } } protected function startswith($string1, $string2) { return strpos($string1, $string2) === 0; } protected function close() { try { /*if ($this->statement != null) $this->statement->close(); if ($this->db != null) $this->db->close();*/ } catch (exception $e) { $e->getmessage(); } } } ?>
there multiple issues class:
- in php 5.x should define constructor
public function __construct()
- the class constructor should not ant computation
- you should not have hard-coded settings connection (provide them parameter in constructor)
- this code ignores many useful elements of pdo, : named parameters, value types, etc.
- there should not
echo
's within class
anyway, responsibility of class ?
if want abstract logic handles data interaction database, should try implement datamapper patterns instead.
Comments
Post a Comment