プログラミング系のネタをまとめていきます。

シングルトン


●ソースコード

class Singleton
{
	private static $instance = null;
	
	// コンストラクタ。privateなので、new が禁止される。
	private function __construct()
	{
		echo 'singleton> '.get_class($this).'.__construct()<br>';
	}
	
	static public function getInstance()
	{
		if($instance == null) $instance = new Singleton;
		return $instance;
	}
}

Singleton::getInstance();	// シングルトンアクセス

$obj = new Singleton();		// エラー


●出力結果

singleton> Singleton.__construct()
Fatal error: Call to private Singleton::__construct() from invalid context in /web/com/139023473323246/main.php on line 26


PDOを使ってMySQLを操作

データベース接続


try
{
	$host_name = 'localhost';
	$db_name = 'test_db';
	$dsn = "mysql:host=$host_name;dbname=$db_name;charset=sjis";

	$user = 'root';
	$password = 'root';

	// PDOインスタンス生成(データベース接続)
	$dbh = new PDO($dsn, $user, $password);
}
catch(PDOException $e)
{
	print("database connection error.<br>");
}

データベースからレコード取得


$dbh;	// PDOインスタンス

try
{
	// SQLステートメント。 :user_id はプレースメントホルダ。bindValue()で値がセットされる。
	$sql = 'select * from test_table where user_id = :user_id';
	
	// SQLステートメントの準備。後で、execute()で実行する。
	$stmt = $dbh->prepare($sql);
	
	// ステートメント内のプレースメントホルダに値を設定
	$stmt->bindValue(':user_id', $id, PDO::PARAM_STR);
	
	// SQLステートメントを実行
	$flag = $stmt->execute();
	
	if($flag)
	{
		// 結果セットから全ての行を配列で取得
		$records = $stmt->fetchAll();
		
		// レコード数
		$num = count($records);
		
		if($num > 0)
		{
			// 1件目のレコードを出力
			var_dump($records[0]);
			
			// 1件目のレコードのカラム'name'の値を出力
			var_dump($records[0]['name']);
		}
	}
}
catch(PDOException $e)
{
	print('Error : '.$e->getMessage());
}

データベース切断


$dbh;	// PDOインスタンス

// 切断
$dbh = null;	// unset($dbh); でも同様

タグ

Menu

メインコンテンツ

プログラミング

機器

Macツール

各種情報

Wiki内検索

おまかせリンク

Androidアプリ

AdSense

技術書


管理人/副管理人のみ編集できます