1 <?php 2 class link_mysql{ 3 //1.declear the variable.but without assignment sentence 4 //2.assignment sentence can only occur in a function body. 5 //3.'website' is a default db,you can switch db use function switch_db; 6 //4.to call a function a variable in class,you should use 'this' pointer. 7 private $host,$uid,$pwd,$db,$link; 8 9 public function __construct($host,$uid,$pwd,$db){ 10 $this->host = $host; 11 $this->uid=$uid; 12 $this->pwd = $pwd; 13 $this->db=$db; 14 $this->link = mysql_connect($this->host,$this->uid,$this->pwd) or 15 die('Not connect to mysql '.mysql_error()); 16 $this->switch_db($this->db); 17 mysql_query('set names utf8'); 18 } 19 //切换数据库的,所以脱离于构造函数 20 public function switch_db($db){ 21 mysql_select_db($db,$this->link); 22 } 23 //执行sql语句 24 public function sql_query($sql){ 25 $res = mysql_query($sql,$this->link); 26 $this->check_res($res); 27 return $res; 28 } 29 //取得结果数目 30 public function get_nums($tb){ 31 $res = mysql_query("select count(*) as num from ".$tb); 32 $this->check_res($res); 33 $count_arr = mysql_fetch_array($res); 34 return $count_arr[0]; 35 } 36 //取得多行多列的结果,得到一个二维数组 37 public function get_all($sql){ 38 $res = mysql_query($sql,$this->link); 39 $this->check_res($res); 40 $arr = array(); 41 while($row = mysql_fetch_assoc($res)){ 42 $arr[] = $row; 43 } 44 return $arr; 45 } 46 //取得单行的结果,取得单行结果 47 public function get_row($sql){ 48 $res = mysql_query($sql,$this->link); 49 $this->check_res($res); 50 $row = mysql_fetch_assoc($res); 51 return $row; 52 } 53 //取得单个结果,一个字符串,由于我门不知道索引值,所以只能用mysql_fetch_array 54 public function get_one($sql){ 55 $res = mysql_query($sql,$this->link); 56 $this->check_res($res); 57 $row = mysql_fetch_array($res); 58 return $row[0]; 59 } 60 //检查资源是否为空 61 private function check_res($res){ 62 if($res){ 63 return false; 64 } 65 } 66 //析构函数 67 public function __destruct(){ 68 mysql_close($this->link); 69 } 70 71 } 72 73 $link = new link_mysql('hostname','username','password','dbname'); 74 $count = $link->get_nums('tablename'); 75 echo 'The nums of table **** is :'.$count; 76 unset($link); 77 ?>