php mysql資料庫類(php新手入門)

來源:互聯網
上載者:User
  1. //by http://bbs.it-home.org

  2. class mySql{
  3. private $result;
  4. private $conn;
  5. public static $hasNew = false;
  6. private __construct(){}
  7. function __destruct(){
  8. self::$hasnew=false;
  9. }

  10. function doNew(){

  11. if(self::$have_new){
  12. exit('資料庫只能串連一次!');
  13. }else{
  14. self::$hasNew=true;
  15. return new self;
  16. }
  17. }
  18. private function connect($host,$user,$password,$dbname,$charset='utf8'){
  19. $this->conn = mysql_connect($host,$user,$password) or exit('錯誤碼:'.mysql_errno(). '資料庫連接失敗:'.mysql_error());
  20. mysql_select_db($dbname,$this->conn) or exit('錯誤碼:'.mysql_errno().'選擇資料庫失敗:'.mysql_error());
  21. mysql_query("set names $charset",$this->conn);
  22. }

  23. function query($sql,$buffer=true){

  24. //mysql_real_escape_string($sql,$this->conn);//特殊字元義
  25. if($buffer){
  26. $this->result=mysql_query($sql,$this->conn) or exit('錯誤碼:'.mysql_errno().'sql語句執行失敗:'.mysql_error());
  27. }else{
  28. $this->result=mysql_unbuffered_query($sql,$this->conn) or exit('錯誤碼:'.mysql_errno().'sql語句執行失敗:'.mysql_error());
  29. }
  30. }
  31. function getRecord(){
  32. return mysql_fetch_array($this->result);
  33. }
  34. function close(){
  35. mysql_free_result($this->result);
  36. mysql_close($this->conn);
  37. }

  38. }

複製代碼

2、調用樣本

  1. //資料庫

  2. $db_host='localhost';
  3. $db_user='root';
  4. $db_pwd='root';
  5. $db_name='news';
  6. $charset='utf8';
  7. $sql="select * from news_base";

  8. $db=mySql::doNew();

  9. $db->connect($db_host,$db_user,$db_pwd,$db_name,$charset='utf8');
  10. $db->query($sql);
  11. while($row=$db->getRecord()){
  12. echo $row[1].'
    ';
  13. }

複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.