kompass/includes/DatabaseHandler.php

61 lines
1.6 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace Bdp\Libs;
class DatabaseHandler {
public function readFromDb(string $table, array $conditions = []) : array {
global $wpdb;
$sql = 'SELECT * FROM ' . $wpdb->prefix . $table . $this->parseConditions($conditions);
return $this->getResults( $sql );
}
public function readSqlFromDb(string $tableName, string $preparedSql) : array
{
global $wpdb;
$sql = str_replace('%tablename%', $wpdb->prefix . $tableName, $preparedSql );
return $this->getResults($sql);
}
public function insertRows(string $tableName, array $newData) : int
{
global $wpdb;
$tableName = $wpdb->prefix . $tableName;
$wpdb->insert( $tableName, $newData );
return $wpdb->insert_id;
}
public function updateRows(string $tableName, array $newData, $conditions = [])
{
global $wpdb;
$tableName = $wpdb->prefix . $tableName;
$wpdb->update( $tableName, $newData, $conditions );
}
public function countSqlRows(string $tableName, array $conditions = []) : int
{
global $wpdb;
$sql = 'SELECT COUNT(*) as count_data FROM ' . $wpdb->prefix . $tableName . $this->parseConditions($conditions);
$res = $this->getResults( $sql );
$res = $res[0];
return (int)$res->count_data;
}
private function getResults(string $sql) : array
{
global $wpdb;
return $wpdb->get_results($sql, OBJECT );
}
private function parseConditions(array $conditionArray) : string
{
global $wpdb;
$_tmpArr = [];
foreach ($conditionArray as $key => $value) {
$_tmpArr[] = '`' . $key .'` = "' . $wpdb->_real_escape($value) . '"';
}
$returnString = implode(' AND ', $_tmpArr);
return $returnString !== '' ? (' WHERE ' . $returnString) : '';
}
}