kompass/includes/DatabaseHandler.php

71 lines
1.9 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);
}
2024-05-27 16:59:30 +02:00
public function deleteFromDb(string $table, array $conditions = []) {
global $wpdb;
$table = $wpdb->prefix . $table;
$wpdb->delete($table, $conditions);
}
public function insertRows(string $tableName, array $newData) : ?int
{
global $wpdb;
$tableName = $wpdb->prefix . $tableName;
2024-05-27 16:59:30 +02:00
if (!$wpdb->insert( $tableName, $newData )) {
return null;
};
return $wpdb->insert_id;
}
public function updateRows(string $tableName, array $newData, $conditions = [])
{
global $wpdb;
$tableName = $wpdb->prefix . $tableName;
2024-05-27 16:59:30 +02:00
return $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) : '';
}
}