I have a mySQL class to connect and execute my queries from and in to a database. When i connect to the database everything is working correctly. When i try to put something into the database, then it's also ok, but when i try to get something from it, I get a boolean (true) error, regardless the input. I assume it must return an object but it returns a boolean. Why is that so?
My code is shown below:
class Database {
function __construct() {
// пустой инициализатор
$this->set_connection(); // нужно ли автоматически инициализировать?
}
private $dbchar = "UTF8";
private $dbuser = "admin";
private $dbpass = "1234";
private $dbhost = "localhost";
private $dbname = "core_db";
private $dbpref = "pre_";
private $link;
private function set_connection() {
$dsn = "mysql:host=".$this->dbhost.";dbname=".$this->dbname.";charset=".$this->dbchar;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
//PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
// Выключает режим эмуляции! если у вас проблемы с LIMIT ?,?
PDO::ATTR_EMULATE_PREPARES => TRUE
);
try {
$this->link = new PDO($dsn, $this->dbuser, $this->dbpass, $opt);
if (!$this->link) throw new Exception("Cannot connect to database!", 4);
} catch (Exception $e) {
die("Error! " . $e->getMessage());
}
}
// Получаем ссылку на соединенние с базой
function get_connection() {
return $this->link;
}
/*
НЕ УДАЛЯТЬ ---------------------------------------------------------
Запросы можно использовать вот так.................!
# просто испольняет SQL запрос // INSERT. DELETE OR UPDATE
$this->execute_query($sql);
$this->execute_query($sql, $data);
# all rows
$result = $this->execute_query($sql, $data)->fetchAll();
foreach ($result as $row) echo $row['name'];
# one row
$row = $this->execute_query($sql, $data)->fetch();
# one cell
$count = $this->execute_query($sql)->fetchColumn(); // можно использовать для подсчета ячеекы
# column
$ids = $this->execute_query($sql)->fetchAll(PDO::FETCH_COLUMN);
НЕ УДАЛЯТЬ ---------------------------------------------------------
*/
// метод выполнения запроса SQL !!!
// Использ. $sql = SELECT * FROM table WHERE a = ? and b = ?
// Использ. $data = array('a', 'b');
function execute_query($sql, $elements=false) {
$error_exist = false;
$data = false;
try {
if (empty($sql)) throw new RuntimeException('no SQL!');
$stmt = $this->get_connection()->prepare($sql);
if (!$stmt) throw new RuntimeException('SQL preparing failure!');
if (!$elements) {
$data = $stmt->execute();
} else {
$data = $stmt->execute($elements);
}
if (!$data) throw new RuntimeException('SQL execution failure!');
} catch (Exception $e) {
$error_exist = true;
$data = $e->getMessage();
}
return array('error' => $error_exist, 'result' => $data);
}
// Закрываем соединение с базой
function close_connection() {
$this->link = null;
}
function __destructor() {
$this->close_connection();
}
}
The index.php
file itself is shown here instead:
$sql = "SELECT * FROM prava WHERE test_id = ?";
$r = $db->execute_query($sql, ['1']);
var_dump($r);