จากการได้ดู video ของ คุณ U แล้วเลยมาลองเขียนเองแต่เกิดการ error ครับ Error ขึ้นว่า "No database selected" ซึ่งผมไม่รู้จะแก้ยังไงให้มัน connect กับตัว databast ได้สะที่ Connect Database
<?php
error_reporting(E_ALL);
class ConnectDB
{
protected $icon;
private $_result;
private $_num_rows;
private $_fetch_array = array();
public function connect()//connect
{
$this->icon=mysql_connect("localhost","root","") or die (mysql_error());
mysql_query ("SET NAMES UTF8");
mysql_select_db("project1") or die (mysql_error());
echo "connect";
return $this->icon;
}
public function _query($res) // mysql_query
{
echo $res;
return $this->_result = mysql_query($res);
}
public function _num_rows() // mysql_num_rows
{
return mysql_num_rows($this->_result);
}
public function _fetch_array() // mysql_fetch_array
{
return $this->_fetch_array=mysql_fetch_array($this->_result);
}
}
$objcon=new ConnectDB();
$objcon->_query("select * from member") or die (mysql_error());
echo $objcon->_num_rows() or die (mysql_error());
echo $objcon->_fetch_array() or die (mysql_error());
?>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<?php
class mySQL{
var $host;
var $username;
var $password;
var $database;
public $dbh; //Variable for storing connection
public function connect($set_host, $set_username, $set_password, $set_database){
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$this->database = $set_database;
$this->dbh = mysql_connect($this->host, $this->username, $this->password)or die("cannot connect"); //Store data connection specifier in object
mysql_query("SET NAMES UTF8");
mysql_query("SET character_set_results=utf8");
mysql_query("SET character_set_client=utf8");
mysql_query("SET character_set_connection=utf8");
mysql_select_db($this->database)or die("cannot select DB");
}
public function query($sql)
{
return mysql_query($sql,$this->dbh); //Specify connection handler when doing query
}
public function fetch($sql)
{
return mysql_fetch_array($this->query($sql));
}
}
$connect = new mySQL();
$connect->connect('localhost', 'root', '', 'project1');
$settings_query = mysql_query("SELECT * FROM member", $connect->dbh); //Specify connection handler when doing query
$settings = mysql_fetch_array($settings_query);
//With query method in object you can do this:
$settings_query = $connect->query("SELECT * FROM member"); //Use object method to query
$settings = mysql_fetch_array($settings_query);
//with fetch method in object you can just do this:
$settings = $connect->fetch("SELECT * FROM member");
//echo $settings['test'];
?>