1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PDOを使用してMySQL接続メモ

Last updated at Posted at 2017-07-12

##はじめに
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();
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?