Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class pdo_handler{
- public $DBH;
- //Connection, MIGHT OUTSOURCE IT TO INDIA (aka another file).
- public function __construct(){
- $host = 'localhost';
- $dbname = 'wedding';
- $user = 'root';
- $pass = 'root';
- try{
- //MySQL with PDO_MYSQL
- $this->DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
- }catch(PDOException $e){
- echo $e->getMessage();
- }
- }
- //Function to insert data, takes an associative array, builds a strings to insert data securely using PDO in the table specified.
- public function insert($array, $table){
- $string = '';
- foreach($array as $key => $value){
- $string .= ":" . $key . ", ";
- }
- $string = substr($string, 0, -2);
- $STH = $this->DBH->prepare("INSERT INTO $table values(" . $string . ")");
- $STH->execute($array);
- }
- //Takes an associate array with all the values to be changed, $table is a string containing the table name, and the condition is a string containing any desired condition.
- public function update($array, $table, $condition = ''){
- $string = '';
- foreach($array as $key => $value){
- $string .= "$key = :" . $key . ", ";
- }
- $string = substr($string, 0, -2);
- $STH = $this->DBH->prepare("UPDATE $table SET $string $condition");
- $STH->execute($array);
- }
- //Delete
- public function delete($table, $condition = ''){
- $STH = $this->DBH->prepare("DELETE from $table $condition");
- $STH->execute();
- }
- //Select function returns an array with all the rows affected, each array has all the column names requested, also returns the [rows] affected
- public function select($what, $where){
- $i = 0;
- $select = array();
- $STH = $this->DBH->query("SELECT $what from $where");
- $STH->setFetchMode(PDO::FETCH_ASSOC);
- while($row = $STH->fetch()){
- foreach($row as $key => $value){
- $select[$i][$key] = $value;
- }
- $i++;
- }
- $data = array(
- 'select' => $select,
- 'rows' => $i
- );
- return $data;
- }
- //Accepts a string for simple existance comparison in another table
- public function exists($what, $where){
- $data = $this->select("*", "$where where $what");
- if($data['rows'] == 0){
- return false;
- }else{
- return true;
- }
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement