Продолжаю работать над своей учебной CMS. И наконец-то осилил класс для работы с базой данных MySQL. Для меня это был не простой опыт, было много ошибок и даже хотелось просто взять чужую библиотеку и на этом успокоиться.
Кстати мне кажется использование чужих библиотек это вовсе даже и неплохо, но не в данном проекте. Это не коммерческий а учебный проект и мне кажется что, для того чтоб научиться лучше хотя-бы попытаться всё сделать самому.
Класс получлся простой и я думаю в последствии он будет ещё не раз улучшаться. Хотябы потому-что я пока понятия не имею как устроены сложные запросы. Читал о них, но не знаю как использовать.
Следовательно весь класс заточен под простые запросы. В нём всего 4 метода и конструктор.
Конструктор задаёт параметры для подключения, методы отвечают за виды запросов
- select — простая выборка
- insert — вставка
- update — обновление
- delete — удаление
<?php
class DatabaseMysql
{
public $pdo;
public function __construct()
{
$options = [
\PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false
];
$dbConfig = require('./core/config/DbConfig.php');
$this->pdo = new \PDO(
'mysql:host=' . $dbConfig['db_host'] . ';dbname=' . $dbConfig['db_name'] . ';charset=utf8mb4',
$dbConfig['db_user'],
$dbConfig['db_pass'],
$options
);
}
/**
* Простой запрос на выборку данных из таблицы
*
* @param string $query
* @param array $params
* @return void
*/
public function select(string $query, array $params = [])
{
$sth = $this->pdo->prepare( $query );
$res = $sth->execute( $params );
if ( false === $res ) {
return null;
}
return $sth->fetchAll( PDO::FETCH_ASSOC );
}
/**
* Простой запрос на запись данных в таблицу
*
* @param string $query
* @param array $params
* @return void
*/
public function insert(string $query, array $params = [])
{
$sth = $this->pdo->prepare($query);
$res = $sth->execute($params);
if (false === $res) {
return null;
}
return $this->pdo->lastInsertId();
}
/**
* Простой запрос на обновление данных в таблице
*
* @param string $query
* @param array $params
* @param boolean $row
* @return void
*/
public function update(string $query, array $params = [], $row = false)
{
$sth = $this->pdo->prepare($query);
$sth->execute($params);
if (true === $row) {
$updates = $sth->rowCount();
return $updates;
}
}
/**
* Простой запрос на удаление данных из таблицы
*
* @param string $query
* @param array $params
* @param boolean $row
* @return void
*/
public function delete(string $query, array $params = [], $row = false)
{
$sth = $this->pdo->prepare($query);
$sth->execute($params);
if (true ===$row) {
$delete = $sth->rowCount();
return $delete;
}
}
}
Понимаю, что это не вершина мастерства, но надеюсь что для моего уровня вполне не плохо.
Если понравилась статья, поставьте, пожалуйста, лайк!
Если Вы интересуетесь программированием на PHP и созданием сайтов — подписывайтесь, и комментируйте материал. Будем учитсья вместе.
Если Вы специалист и случайно наткнулись на мою статью, пожалуйста укажите на ошибки, скажите где копать. Возможно именно ваш совет поможет мне и другим избежать большого количества ошибок на пути обучения программированию.
Taxi moto line
128 Rue la Boétie
75008 Paris
+33 6 51 612 712
Taxi moto paris
Good day! This is my 1st comment here so I just wanted to give a
quick shout out and say I truly enjoy reading your blog
posts. Can you suggest any other blogs/websites/forums that go over the same topics?
Thanks a lot!
Good way of describing, and good article to take data about my presentation subject, which i am going to convey in school. Drona Maurise Pearce
Looking forward to reading more. Great article post. Much thanks again. Want more. Jessamyn Wait Gentes Nydia Robbert Odrick
I have to get across my love for your generosity for men and women that absolutely need assistance with in this concern. Your real dedication to passing the solution all around was pretty interesting and have regularly allowed many people like me to achieve their targets. This warm and helpful guideline entails a lot a person like me and extremely more to my office workers. Thanks a lot; from each one of us. Katya Othello Darbee
It can be very helpful to watch professional players who share your same position on the field. Joete Maxie Mazel
You should participate in a contest for among the best blog sites online. I will suggest this website! Nicoline Peter Bonina
This piece of writing gives clear idea in favor of the new users of blogging, that truly how to do blogging. Em Guntar Fujio
I love your projects and your creativity! Please consider doing more thrifty stuff and maybe none of the dollar store stuff. Dollar stores are predatory to already marginalized people. Audrye Schuyler Weixel
I enjoy the efforts you have put in this, appreciate it for all the great content. Addy Payton Russi
An impressive share, I just offered this onto a coworker that was doing a little analysis on this. And he in fact acquired me morning meal due to the fact that I discovered it for him. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for investing the time to discuss this, I really feel strongly about it as well as enjoy learning more on this subject. When possible, as you come to be expertise, would you mind upgrading your blog with even more information? It is very useful for me. Large thumb up for this post! Josephina Brandtr Armin
After looking over a number of the articles on your website, I really appreciate your technique of blogging. I book-marked it to my bookmark site list and will be checking back in the near future. Please visit my web site as well and tell me your opinion. Lauraine Nikola Almire
usually posts some quite exciting stuff like this. If youre new to this site Romy Lindsey Laufer
Ah, this is a very good list of some of the very best kayaks to buy for a quite cheap price considering how valued kayaks are. I only have a problem of choosing which of your recommendation is the best for me. I hope you are able to reply me and tell me which of the different types of fishing kayaks you have here is the best. Genny Whitney Fruma