Php database mysql framework

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A MySQL ODM (assistant) extremely flexible for any project.

License

wcatron/MySQL-Framework-PHP

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Читайте также:  Getting the Value of Bean

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A MySQL ODM (assistant) extremely flexible for any project.

This framework allows you to quickly map objects to rows in a MySQL database.

Create models for your objects and have them extend Row. Implement the toRow and fromRow methods and set the TABLE and ID_COLUMN constants. Call MyDB::configure() in your autoload.php file or wherever needed before database calls. You can now perform queries and get php objects back.

composer require wcatron/mysql-db-framework 

Your classes. Add two functions and two constants and allow any model to create objects.

class Your Class extends Row < /** @var LinkedObject */ var $linkedObject; const TABLE pl-s">table"; const ID_COLUMN pl-s">table_id"; function __construct() < $this->setObjectForKey(LinkedObjectClass::class, 'linked_id', 'linkedObject'); > function toRow() < $row = parent::toRow(); // . Add your fields to the row. return $row; > function fromRow($row) < parent::fromRow($row); // . Set your fields. > >

Saving is extremely simple when you have an object whose class extends row.

Your connection to mysql. To get your rows as objects use this singleton MyDB::getInstance()

getObjectByID(Class::class,$id)

Alternatively you can just call getByID($id) on your custom Row object.

This will return your exact object.

getObjectsWithQuery(Class::class,$query)

An array of objects based on a custom query. Not all queries need to be written out though.

getObjectByColumn(Class::class, ‘ColumnName’, $value)

If you’re only searching by one column use this simple function.

About

A MySQL ODM (assistant) extremely flexible for any project.

Источник

Database — библиотека на PHP для работы с MySql. Презентация решения

Не так давно я устроился на новую работу и впервые столкнулся с популярным фреймворком. Мне необходимо было написать большой SQL-запрос. Я его написал, сделал bindValue, запустил сценарий и… запрос завершился с ошибкой. Я очень надеялся, что фреймворк позволит мне получить полноценный SQL-запрос, что бы я смог его отладить. Но не тут то было — фреймворк не позволял сделать ничего подобного. Ровно, как и PDO/mysqli не позволяют этого до сих пор.

Современные средства для работы с базой MySql в PHP, будь то абстракция PDO или расширения mysql и mysqli — просто не предназначены для «клиентского» кода. Об этом очень хорошо написали на хабре еще в 2012 году. Есть две основных причины, по которым использовать родные инструменты в «голом» виде просто невозможно. Это:

  • Многословность — на каждый запрос приходится писать по несколько однотипных строк кода
  • Невозможность получить SQL запрос для отладки — функция, которой просто катастрофически не хватает

В библиотеке два основных метода для выполнения запросов — методы query() и queryArguments(), работающих в составе обертки над стандартным объектом mysqli. Эти методы возвращают результативный объект, который также представляет собой обертку над стандартным mysqli_result.

Все просто и ясно. Ничего лишнего.

Основное достоинство библиотеки — это эмуляция подготовленных запросов, удобная работа с заполнителями (placeholders). Параметры запроса передаются отдельно от SQL, а в самом SQL на месте, где должны присутствовать параметры запроса, пишутся специальные типизированные маркеры. Парсер библиотеки находит эти маркеры, определяет их тип и в зависимости от типа маркеров, занимается преобразованием параметров запроса и их подстановкой в исходную строку SQL-запроса.

setDatabaseName("test") // Выбор кодировки ->setCharset("utf8"); // Получение объекта результата Database_Mysql_Statement // Database_Mysql_Statement - "обертка" над "родным" объектом mysqli_result $result = $db->query("SELECT * FROM `users` WHERE `name` = '?s' AND `age` = ?i", "Д'Артаньян", 30); // Получаем данные (в виде ассоциативного массива, например) $data = $result->fetch_assoc(); // Получим количество рядов в результате $result->getNumRows(); // Не работает запрос? Не проблема - выведите его на печать: echo $db->getQueryString(); // Получить все SQL-запросы текущего соединения print_r($db->getQueries()); 
  • Ваш код становится короче — выполнение запросов пишется в одну строку
  • Надежная защита от SQL-инъекций. Никаких mysqli_real_escape_string() и intval()
  • Экранирование символов для оператора LIKE
  • Несколько полезных плейсходеров — как для подготовки скалярных типов, так и создания множеств из массивов
  • Возможность получать все SQL-запросы текущего соединения, как до процедуры парсинга, так и после
  • Прозрачный и понятный код, доступный для расширения и модификации

Источник

The Lightweight PHP Database Framework to Accelerate Development

Supports various common and complex SQL queries, data mapping, and prevents SQL injection.

Compatible

Supports MySQL, MSSQL, SQLite, MariaDB, PostgreSQL, Sybase, Oracle, and more.

Friendly

Works well with every PHP framework, like Laravel, Yii, Slim, and framework which supports singleton extension or composer.

Free

Under the MIT license, you can use it anywhere, whatever you want.

Get Started

Composer require

Update

// Require Composer's autoloader. require 'vendor/autoload.php'; // Using Medoo namespace. use Medoo\Medoo; // Connect the database. $database = new Medoo([ 'type' => 'mysql', 'host' => 'localhost', 'database' => 'name', 'username' => 'your_username', 'password' => 'your_password' ]); $database->insert('account', [ 'user_name' => 'foo', 'email' => 'foo@bar.com' ]); $data = $database->select('account', [ 'user_name', 'email' ], [ 'user_id' => 50 ]); echo json_encode($data); // [< // "user_name" : "foo", // "email" : "foo@bar.com" // >]

Sponsors

Medoo is an open-source project under the MIT license and will always be free to use. However, the project needs some funding every month to sustain itself. Any sponsorship for the project will be beneficial for us to build Medoo better for all PHP developers in the world, and we will put your company logo on the homepage as appreciation.

1rJMEJtfFWoCQHxoP5Two8R9gXS9y9C4k —>

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

The lightweight PHP database framework to accelerate the development.

License

catfan/Medoo

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

The lightweight PHP database framework to accelerate development.

  • Lightweight — Portable with only one file.
  • Easy — Easy to learn and use, with a friendly construction.
  • Powerful — Supports various common and complex SQL queries, data mapping and prevents SQL injection.
  • Compatible — Supports MySQL, MSSQL, SQLite, MariaDB, PostgreSQL, Sybase, Oracle, and more.
  • Friendly — Works well with every PHP framework, such as Laravel, Codeigniter, Yii, Slim, and frameworks that support singleton extension or composer.
  • Free — Under the MIT license, you can use it anywhere, for whatever purpose.

PHP 7.3+ and installed PDO extension.

Add Medoo to the composer.json configuration file.

$ composer require catfan/medoo 
// Require Composer's autoloader. require 'vendor/autoload.php'; // Use the Medoo namespace. use Medoo\Medoo; // Connect to the database. $database = new Medoo([ 'type' => 'mysql', 'host' => 'localhost', 'database' => 'name', 'username' => 'your_username', 'password' => 'your_password' ]); $database->insert('account', [ 'user_name' => 'foo', 'email' => 'foo@bar.com' ]); $data = $database->select('account', [ 'user_name', 'email' ], [ 'user_id' => 50 ]); echo json_encode($data); // [ // "user_name" : "foo", // "email" : "foo@bar.com", // >]

Before starting a new pull request, please ensure compatibility with other databases and write unit tests whenever possible.

Run phpunit tests for unit testing and php-cs-fixer fix to fix code style.

Each commit should start with a tag indicating the type of change: [fix] , [feature] , or [update] .

Please keep it simple and keep it clear.

Medoo is released under the MIT license.

Support Our Other Product

Gear Browser

About

The lightweight PHP database framework to accelerate the development.

Источник

Оцените статью