ImI'm trying to get familiarefamiliar with (i dont even know how this is called) database handling
Can. Can you guys point out my errors and what iI should change?
I
I want to learn new methods, ibut just dontdon't want to learn it the wrong way.
PS. iI do realize these things below, yet iI wanted to make the code more clear
:
- iI need to bind values for insert
insert()
- use tryUse
try/catchcatch for error handling
_db = new PDO('mysql:host=localhost;dbname=mvc;', 'root', '');
$this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->_db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
public function select($arg)
{
$this->_sql .= "SELECT {$arg}";
return $this;
}
public function from($arg)
{
$this->_sql .= " FROM {$arg}";
return $this;
}
public function insert($arg)
{
$this->_sql .= "INSERT INTO {$arg}";
return $this;
}
public function columns($arg)
{
$this->_sql .= " ({$arg})";
return $this;
}
public function values($arg)
{
$this->_sql .= " VALUES ({$arg})";
return $this;
}
public function execute($data = null)
{
$this->_sth = $this->_db->prepare($this->_sql);
$this->_sth->execute($data);
$this->_sql = null;
return $this;
}
public function fetch()
{
return $this->_sth->fetchAll();
}
public function getSql()
{
return $this->_sql;
}
}
$query = new Query;
// inserts into database
$query->insert('users')
->columns('`username`,`password`')
->values('"test","tester"')
->execute();
// returns array of users
$query->select('username')
->from('users')
->execute()
->fetch()
?>
<?php
class Query
{
private $_sql;
private $_sth;
private $_db;
public function __construct()
{
$this->_db = new PDO('mysql:host=localhost;dbname=mvc;', 'root', '');
$this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->_db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
public function select($arg)
{
$this->_sql .= "SELECT {$arg}";
return $this;
}
public function from($arg)
{
$this->_sql .= " FROM {$arg}";
return $this;
}
public function insert($arg)
{
$this->_sql .= "INSERT INTO {$arg}";
return $this;
}
public function columns($arg)
{
$this->_sql .= " ({$arg})";
return $this;
}
public function values($arg)
{
$this->_sql .= " VALUES ({$arg})";
return $this;
}
public function execute($data = null)
{
$this->_sth = $this->_db->prepare($this->_sql);
$this->_sth->execute($data);
$this->_sql = null;
return $this;
}
public function fetch()
{
return $this->_sth->fetchAll();
}
public function getSql()
{
return $this->_sql;
}
}
$query = new Query;
// inserts into database
$query->insert('users')
->columns('`username`,`password`')
->values('"test","tester"')
->execute();
// returns array of users
$query->select('username')
->from('users')
->execute()
->fetch()
?>