46 lines
1.3 KiB
PHP
46 lines
1.3 KiB
PHP
<?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 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) : '';
|
|
}
|
|
} |