//mysql基本連線方式
mysql_connect('localhost','root','password');
mysql_select_db('mydb');
mysql_query("SET NAMES 'utf8'");
$sql = "SELECT * FROM `user` WHERE name = 'sam'";
$result = mysql_query($sql);
if($result != false)
while($row = mysql_fetch_object($result)){
echo $row->name.'<br/>';
}
}
////////////// 變成建構式
class db{
public $host = 'localhost';
public $username = 'root';
public $password = 'password';
public $database = 'mydb';
function __construct($keyin){
$this->key1 =$keyin;
$this->sql_connect();
$this->sql_database();
$this->set_db_encode($key1);
}
function sql_connect(){
return @mysql_connect($this->host,$this->username,$this->password);
}
function sql_database(){
return @mysql_select_db($this->database);
}
function set_db_encode($key2){
$this->key3 =$key2;
return mysql_query($key3);
}
}
$db = new db("SET NAMES 'utf8'");
//////////////////
class db{
public $host = 'localhost';
public $username = 'root';
public $password = 'password';
public $database = 'mydb';
public $result;
function __construct(){
$this->sql_connect();
$this->sql_database();
$this->set_db_encode();
}
function sql_connect(){
return @mysql_connect($this->host,$this->username,$this->password);
}
function sql_database(){
return @mysql_select_db($this->database);
}
function set_db_encode(){
return mysql_query("SET NAMES 'utf8'");
}
function query($sql_string){
$result = mysql_query($sql_string);
$query = new db_query($result);
return $query;
}
}
class db_query{
private $result;
function __construct($result){
$this->result = $result;
}
function result(){
$query = array();
if($this->result != false){
while($row = mysql_fetch_object($this->result)){
$query[] = $row;
}
return $query;
}
return false;
}
}
$db = new db();
$query = $db->query("SELECT * FROM `user` WHERE name = 'sam'"); // 如同 $query = new db_query 一般
foreach($query->result() as $row){
echo $row->name.'<br/>';
}
//clase db --> opne db --> db_query
留言列表