1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
<?php
class dao
{
private $db = NULL;
private $connection_string = NULL;
private $db_host = DB_HOST;
private $db_user = DB_USER;
private $db_pass = DB_PASS;
private $db_name = DB_NAME;
private $con = false;
private $result = array();
public function __construct($db_user = DB_USER, $db_pass = DB_PASS, $db_name = DB_NAME, $db_type = 'mysql', $db_host = 'localhost')
{
$this->db_host = $db_host;
$this->db_user = $db_user;
$this->db_pass = $db_pass;
$this->db_name = $db_name;
$this->connection_string = "mysql:host=".$db_host.";dbname=".$db_name;
return $this;
}
public function connect()
{
if(!$this->con)
{
try {
$this->db = new PDO($this->connection_string,$this->db_user,
$this->db_pass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->con = true;
return $this->con;
}
catch (PDOException $e)
{
return $e->getMessage();
}
}
else
{
return true; //already connected, do nothing and show true
}
}
public function disconnect()
{
if($this->con)
{
unset($this->db);$this->con = false;
return true;
}
}
public function select($table, $rows = '*', $where = null, $order = null)
{
if($this->tableExists($table))
{
$q = 'SELECT '.$rows.' FROM '.$table;
if($where != null)
$q .= ' WHERE '.$where;
if($order != null)
$q .= ' ORDER BY '.$order;
$this->numResults = null;
try {
$sql = $this->db->prepare($q);
$sql->execute();
$this->result = $sql->fetchAll(PDO::FETCH_ASSOC);
$this->numResults = count($this->result);
$this->numResults === 0 ? $this->result = null : true ;
return true;
}
catch (PDOException $e)
{
return $e->getMessage().''.$e->getTraceAsString().'';
}
}
}
public function getResult()
{
return $this->result;
}
public function getRows()
{
return $this->numResults;
}
}
?>
<?php
$db = new dao('user','pass','mabase');
$db->connect();
$result = $db->select('matable');
if ($result === true)
{
echo "result rows ".$db->getRows()." ";
echo "result select ";
print_r($db->getResult());
}
else
{
var_dump($result);
}
$db->disconnect();
?> |
Partager