UMySQL is an extremely simple PHP library for communicating with MySQL databases with ease while keeping overhead to a bare minimum.

Related tags

Miscellaneous umysql
Overview

Uncomplicated MySQL

Build Status Latest Version Minimum PHP Version License

UMySQL is an extremely simple PHP library for communicating with MySQL databases with ease while keeping overhead to a bare minimum. It aims to be an almost 1-to-1 and modern replacement for SafeMySQL.

It doesn't provide any ORM, migration, events, caching, etc. functionality: Just the bare minimum to get you started.

Installation

First of all, make sure your environment meets the following requirements:

Then, you should be able to install this library using Composer:

composer require josemmo/umysql

Usage

Creating a new instance

Typically, you'll want to create a new database instance using connection options:

'app', // Defaults to "root" 'password' => 'S3cret', // Defaults to "" (empty string) 'database' => 'blog', // Defaults to none selected 'port' => 3306, // Defaults to 3306 'charset' => 'utf8mb4' // Defaults to "utf8mb4" ]);">
$db = new UMySQL([
  'hostname' => '127.0.0.1', // Defaults to "localhost"
  'username' => 'app',       // Defaults to "root"
  'password' => 'S3cret',    // Defaults to "" (empty string)
  'database' => 'blog',      // Defaults to none selected
  'port'     => 3306,        // Defaults to 3306
  'charset'  => 'utf8mb4'    // Defaults to "utf8mb4"
]);

You can also connect to a UNIX socket:

$db = new UMySQL([
    'socket'   => '/run/mysqld/mysqld.sock',
    'username' => 'root',
    'password' => 'toor',
]);

As an alternative to options, you can wrap a mysqli instance around a database connection:

$db = new UMySQL(mysqli_connect('localhost', 'root', '', 'blog'));

Writing queries

UMySQL supports various placeholders to safely replace values into queries:

  • ?s for strings, decimals and dates
  • ?i for integers
  • ?n for identifiers (table and column names)
  • ?a for arrays of strings
  • ?u for maps (associative arrays), useful in UPDATE queries
  • ?p for already parsed query parts

Here are some common examples on how to use them:

$db->parse('SELECT * FROM movies');
// SELECT * FROM movies

$db->parse('SELECT * FROM ?n WHERE username=?s AND points>=?i', 'users', 'nick', 100);
// SELECT * FROM `users` WHERE username='nick' AND points>=100

$db->parse('SELECT * FROM products WHERE id IN (?a)', [10, null, 30]);
// SELECT * FROM products WHERE id IN ('10', NULL, '30')

$db->parse('INSERT INTO metrics SET ?u', ['rtt' => 132.22, 'unit' => 'ms']);
// INSERT INTO metrics SET `rtt`='132.22', `unit`='ms'

$db->parse('SELECT * FROM places WHERE city=?s ORDER BY ?n ?p', 'London', 'name', 'ASC');
// SELECT * FROM places WHERE city='London' ORDER BY `name` ASC

Fetching results

The database instance comes with built-in helpers for retrieving rows from the database in a straightforward manner:

  • $db->getAll() to get all rows in a result set
  • $db->getRow() to get only the first row or null in case of an empty result set
  • $db->getCol() to get the values from the first column of a result set
  • $db->getOne() to get the first column from the first row or false in case of an empty result set

Some examples are:

$movies = $db->getAll('SELECT title, year FROM movies');
// [['title' => '...', 'year' => '...'], ['title' => '...', 'year' => '...'], ...]

$product = $db->getRow('SELECT * FROM products WHERE id=?i', 123);
// ['name' => '...', 'price' => '...']

$metrics = $db->getCol('SELECT rtt FROM metrics WHERE created_at>=?s', gmdate('Y-m-d 00:00:00'));
// ['112.12', '128.93', '120.66', '119.34', ...]

$userId = $db->getOne('SELECT id FROM users WHERE username=?s', 'some-username');
// '123'

Executing other queries

For non-SELECT and more advanced queries, UMySQL has a $db->query() method that returns a custom Result instance.

Typically, you'll use this method when you don't care about the result of an operation or when there's no result set:

$db->query('TRUNCATE metrics');
// [\UMySQL\Result]

Result instances are also useful in UPDATE/DELETE operations to get the number of affected rows:

$affectedRows = $db->query('DELETE FROM users WHERE banned=1')->rowCount();
// '123'

Similarly, you can get the last insert ID of an auto-increment column in INSERT operations:

$productId = $db->query('INSERT INTO products (name, price) VALUES (?s, ?s)', 'Something', 12.34)->insertId();
// '321'

These instances can also be used to read a result set at your own pace:

$result = $db->query('SELECT * FROM large_table');
while ($row = $result->fetchRow()) {
    // Do something with `$row`
}
$result->free(); // Optional, will get called after `unset($result)`

Running the test suite

If you want to contribute to this project, please make sure to run the tests before committing new changes.

Tests are run against a MySQL database, so you'll need to define the following environment variables beforehand:

  • DB_HOSTNAME
  • DB_USERNAME
  • DB_PASSWORD (optional)
  • DB_DATABASE
You might also like...
Debug - The Debug component provides tools to ease debugging PHP code.

Debug Component CAUTION: this component is deprecated since Symfony 4.4. Instead, use the ErrorHandler component. The Debug component provides tools t

The ErrorHandler component provides tools to manage errors and ease debugging PHP code

ErrorHandler Component The ErrorHandler component provides tools to manage errors and ease debugging PHP code. Getting Started $ composer require symf

Utility that helps you switch git configurations with ease.

git-profile Utility that helps you switch git configurations with ease Preface It is possible that you have multiple git configurations. For example:

In order to use the Korean Language on your Magento 2 store, it is time to start with Magento 2 Korean Language Pack in the set of informative documentations by Mageplaza. Magento 2 Korean Language Package is published by Magento 2 Translation Project at Crowdin, so all phrases will be replaced by the Korean language according to the contribution to that project. Please following up the guides in this post to convert the language with ease!  A complete solution for group projects in organizations that lets you track your work in any scenario. Working in a team is a cumbersome task, ease it using our project management system.
A complete solution for group projects in organizations that lets you track your work in any scenario. Working in a team is a cumbersome task, ease it using our project management system.

SE-Project-Group24 What is Evolo? Evolo is Dashboard based Project Management System. A complete solution for group projects in organizations that let

This example shows how to use Anychart library with the PHP programming language, Laravel framework and MySQL database.
This example shows how to use Anychart library with the PHP programming language, Laravel framework and MySQL database.

PHP basic template This example shows how to use Anychart library with the PHP programming language, Laravel framework and MySQL database. Running To

🔒 a simple login screen done in php with connection to mysql

login.php What is a login system? login (derived from the English log in) or logon or signin, is the process to access a restricted computer system ma

This is the information I prepared for the PHP interview.The notes include PHP, MySql, Linux, etc.
This is the information I prepared for the PHP interview.The notes include PHP, MySql, Linux, etc.

PHP面试准备的资料 这个项目是自己准备面试整理的资料。可能包括PHP、MySQL等资料。方便自己以后查阅,会不定期更新,如果错误,请指出,谢谢。欢迎大家提交PR,谢谢大家的star 可以通过https://xianyunyh.gitbooks.io/php-interview/预览。欢迎有精力的朋

Releases(v0.0.1)
Owner
José Miguel Moreno
🐱‍💻.tk
José Miguel Moreno
A tool for creating configurable dumps of large MySQL-databases.

slimdump slimdump is a little tool to help you create configurable dumps of large MySQL-databases. It works off one or several configuration files. Fo

webfactory GmbH 176 Dec 26, 2022
An extremely customizable BuildBattle mini-game designed for scalability and simplicity.

BuildBattle An extremely customizable BuildBattle mini-game designed for scalability and simplicity. Features Customisable messages and scoreboard Mul

null 11 Sep 18, 2022
Inventory System for keeping track of your Inventory & Supply.

Inventory System Inventory system to keep track of inventory and supply! Explore the docs » Report Bug · Request Feature Table of Contents About The P

aTq_ 1 Oct 25, 2022
Contracts for Rule Doc Generator. Useful for production code with minimum dependencies.

Rule Doc Generator Contracts Contracts for Rule Doc Generator. Useful for production code with minimum dependencies. Install composer require symplify

null 19 Dec 22, 2022
An all-in-one package with the minimum third-party requirements to get started as quickly as possible with Pokemod Atlas

Pokemod Atlas All-In-One An all-in-one package with the minimum third-party requirements to get started as quickly as possible with Pokemod Atlas. ❤️

Pokemod 12 Oct 10, 2022
A simple PHP package for sending messages to Slack, with a focus on ease of use and elegant syntax.

Slack for PHP A simple PHP package for sending messages to Slack with incoming webhooks, focussed on ease-of-use and elegant syntax. Note: this packag

Regan McEntyre 1.2k Oct 29, 2022
A Pocketmine Plug-in For Executing Commands While You Click on a item

ItemInteract What This Plugin Do? well This Plugin Is Usefull For Some Servers Like minigames,Skyblock,Lobby etc. This plugin can execute commands whi

null 6 May 31, 2022
Allow players to see how well they are doing while pvping with the help of a combo counter

Combo-Counter Allow players to see how well they are doing while pvping with the help of a combo counter Settngs / Config #set to false if you dont wa

null 3 Jun 1, 2022
This plugin gets player time while playing and leaderboard

TopNolep TopNolep is a plugin that retrieves the game time the player was on the server during, not only that, topnolep now provides a leaderboard tha

Edo 5 Oct 22, 2021
A custom twig extension to truncate text while preserving HTML tags.

TwigTruncateExtension A custom twig extension to truncate text while preserving HTML tags. Installation Add the library to your app's composer.json:

dzango 12 Oct 30, 2019