3
4

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 5 years have passed since last update.

PHPで特定のMySQLデータベースに接続するクラス

Posted at

使い方

クラスを初期化するためには、

  • DBユーザー名
  • DBパスワード
  • DBのホスト名
  • DB名
    の4つの変数を引数として渡す必要があります。

実行コード例

//4つの変数に代入する
$dbuser = 'your_name';
$dbpass = 'your_password';
$dbhost = 'localhost';
$dbname = 'test';

//接続を実行する
$db = new connect_db($dbuser,$dbpass,$dbhost,$dbname);

//DB接続時のハンドルをゲットするメソッドを実行
$handle = $db->getHandle();
//上で取得したハンドルを用いてMySQlにリクエストを送る

クラスのソースコード

## データベースに接続するクラス
class connect_db{
	//データベース接続のための変数を宣言
	private $dbuser;
	private $dbpass;
	private $dbhost;
	private $dbname;

	private $handle;


	//コンストラクタでデータベースを設定し自動接続する
	public function __construct($dbuser,$dbpass,$dbhost,$dbname){
		$this->dbuser = $dbuser;
		$this->dbpass = $dbpass;
		$this->dbhost = $dbhost;
		$this->dbname = $dbname;
		$this->connect();
	}

	//データベースに接続
	public function connect(){
		$handle = mysql_connect($this->dbhost, $this->dbuser, $this->dbpass);
		$this->handle = $handle;
		if( mysql_select_db($this->dbname,$this->handle)){
			return 'true';
		}else{
			return'false';
		}
	}
	public function getHandle(){
		return $this->handle;
	}

}

ちょっと無駄があるような気がしますが。
また、セキュリティ的にはどうなのか不安です。

3
4
2

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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?