I'm trying to get familiar with database handling. Can you point out my errors and what I should change?
I want to learn new methods, but just don't want to learn it the wrong way.
I do realize these things below, yet I wanted to make the code more clear:
- I need to bind values for
insert()
- Use
try
/catch
for error handling - Password hashing (did not use it to make example simpler)
<?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()
?>