##はじめに
PDOでMySQLを操作する方法の備忘録です。
PDO接続
autoload.php
spl_autoload_register(function($class) {
$prefix = 'App\\';
if (strpos($class, $prefix) === 0) {
$className = substr($class, strlen($prefix));
$classFilePath = __DIR__ . '/' . str_replace('\\', '/', $className) . '.php';
if (file_exists($classFilePath)) {
require $classFilePath;
}
}
});
config.php
define('DB_HOST', 'localhost');
define('DB_NAME', '****');
define('DB_USERNAME', '****');
define('DB_PASSWORD', '****');
define('DB_DSN', 'mysql:host='. DB_HOST .';dbname='.DB_NAME);
require_once(__DIR__ . '/autoload.php');
Model.php
namespace App;
class Model {
protected $pdo;
public function __construct() {
try {
$this->pdo = new \PDO(DB_DSN, DB_USERNAME, DB_PASSWORD,
[
\PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
\PDO::ATTR_EMULATE_PREPARES => false,
]
);
$this->pdo->query('SET NAMES utf8');
} catch (\PDOException $e) {
echo $e->getMessage();
exit;
}
}
}
index.php
require_once(__DIR__ . '/config.php');
$app = new App\Model();