Designing a database

17 Jan 2017

Schema Naming Conventions

Best pratice, performance tipps

Default Engine/Encoding

To make sure your strings go from PHP to MySQL as UTF-8, make sure your database and tables are all set to the utf8 character set and collation, and that you use the utf8 character set in the PDO connection string.

$pdo = new PDO('mysql:host=127.0.0.1;dbname=test;charset=utf8', 'root', '',
    array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_PERSISTENT => false,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci"
    )
);

Read more: https://stackoverflow.com/a/766996/1461181

Data types

Basic table

CREATE TABLE `tablename` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `created_at` DATETIME DEFAULT NULL,
    `created_user_id` INT(11) DEFAULT NULL,
    `updated_at` DATETIME DEFAULT NULL,
    `updated_user_id` INT(11) DEFAULT NULL,
    PRIMARY KEY (`id`),
    KEY `created_user_id` (`created_user_id`),
    KEY `updated_user_id` (`updated_user_id`)
) ENGINE = INNODB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ;

Basic codelist table (type)

CREATE TABLE `tablename_types` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `title` VARCHAR (255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
    `created_at` DATETIME DEFAULT NULL,
    `created_user_id` INT(11) DEFAULT NULL,
    `updated_at` DATETIME DEFAULT NULL,
    `updated_user_id` INT(11) DEFAULT NULL,
    PRIMARY KEY (`id`),
    KEY `position` (`position`),
    KEY `created_user_id` (`created_user_id`),
    KEY `updated_user_id` (`updated_user_id`)
) ENGINE = INNODB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ;