Using a OOP PDO DB wrapper, Trying to make it so I can add AND
statements to my queries without having multiple queries, For some reason this isn't working but isn't giving
public function query($sql, $params = array()){
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)){
$x = 1;
if(count($params)){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}else{
$this->_error = true;
}
}
return $this;
}
public function action($action, $table, $where = array(), $additional = array()){
if(count($where) === 3){
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(count($additional) === 4) {
$condition = $additional[0];
$field2 = $additional[1];
$operator2 = $additional[2];
$value2 = $additional[3];
}
if(in_array($operator, $operators)){
if(count($additional) === 4){
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ? {$condition} {$field2} {$operator2} ?";
if(!$this->query($sql, array($value, $value2))->error()){
return $this;
}
} else {
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->query($sql, array($value))->error()){
return $this;
}
}
}
}
return false;
}
public function get($table, $where, $additional = array()){
return $this->action('SELECT *', $table, $where, $additional);
}
This is the PHP for DB.php, this is for the class.
public function get($time){
$field = (is_numeric($time)) ? 'week' : 'day';
if($field == "day") {
$week = date("W");
$data = $this->_db->get("timetable", array($field, '=', $time), array('AND', 'week', '=', $week));
} else {
$data = $this->_db->get("timetable", array($field, '=', $time));
}
if($data->count()){
$this->_data = $data->results();
return true;
}
return false;
}
And this is where I'm calling it.
<?php for($i = 0;$i <= 6;$i++){ ?>
<div id="<?php echo $days[$i];?>" class="tab-pane <?php if ($i == $today) { echo "active"; }?>">
<?php
$timetable = new Timetable();
$timetable->get($days[$i]);
echo $days[$i];
if(!empty($timetable->data())) {
foreach ($timetable->data() as $day) {
print_r($day);
}
}
?>
</div>
<?php } ?>
Note - $days
is an array of the days of the week, I'm doing a for to go through each day and get the data for that day, but also for the current week. However also able to get information from a specified week.
Well It is creating the query from $timetable->get($days[$i])
, which inputs into the function public function get($time)
which then uses the get function from the first block of code which uses the action block.
The query I'm using:
SELECT * FROM timetable WHERE day = 'Monday' AND week = 3