PHP MySQL 简介

Three ways to reach MySQL: the removed mysql extension, mysqli and PDO.

Beginner
Key PointsUse PDO for new projects: multiple drivers, named placeholders, exception mode.

Three options

ExtensionStatusMulti-databaseNamed params
mysqlPHP 7.0 已移除否否
mysqli内置否(仅 MySQL)否
PDO内置是(12 种驱动)是

mysql_* functions were removed in PHP 7. Countless old tutorials still use them — copying them fails immediately.

PDO vs mysqli

  • Choose PDO —— driver portability, named placeholders, uniform exceptions
  • Choose mysqli —— MySQL-only with its specific features (async queries, multi_query)
  • Either works —— most code only uses prepare/execute/fetch

What a DSN is

PDO describes a connection as driver:key=value;key=value. **Always include charset=utf8mb4** or Chinese text may corrupt.

PHP
<?php
$dsn = "mysql:host=127.0.0.1;port=3306;dbname=demo;charset=utf8mb4";

foreach (explode(";", substr($dsn, 6)) as $pair) {
    [$k, $v] = explode("=", $pair, 2);
    echo str_pad($k, 8) . "=> " . $v . "\n";
}
Output
host    => 127.0.0.1
port    => 3306
dbname  => demo
charset => utf8mb4

utf8mb4 differs from utf8: MySQL's utf8 is 3-byte only and cannot store emoji. Use utf8mb4 for full Unicode.

Three must-set attributes

AttributeValueWhy
ATTR_ERRMODEERRMODE_EXCEPTION出错抛异常,不会静默返回 false
ATTR_DEFAULT_FETCH_MODEFETCH_ASSOC默认关联数组,不用每次传参数
ATTR_EMULATE_PREPARESfalse用真正的服务端预处理,类型更准
Under the default ERRMODE_SILENT, a failed query just returns false. Forget to check and the page looks fine while SQL fails — the hardest bug class to trace.

Prerequisites

Bash
# 检查扩展是否启用
php -m | grep -E "pdo|pdo_mysql"

# 没有的话装(Debian / Ubuntu)
# apt install php-mysql

# 检查 MySQL 是否在跑
# mysqladmin -u root -p status

pdo and pdo_mysql are separate extensions. With only the former, new PDO("mysql:...") reports could not find driver.

Friends & Partners