PHP學習筆記之串連mysql資料庫

來源:互聯網
上載者:User


果文章出現錯誤,希望各位包涵、指出。

言歸正傳,對於PHP來講,它是預設支援MYSQL的,也就是說我們不必再去手動設定ODBC來使用MYSQL了,我們所需要做的設定就是在php.ini中引入MYSQL外掛程式。首先找到你的php.ini,編輯它,將extension = php_mysql.dll前的分號(“;”)去掉即可。這樣,我們的php就可以使用MYSQL了。

 接下來我們串連mysql,mysql_connect(servername:port,username,password)就是用於串連mysql的函數,其中servername:port參數就是資料庫地址以及資料庫連接埠(預設情況下port參數為3306);username即是登陸資料庫所使用的使用者名稱,password則是對應使用者的密碼。由於我的資料庫就在本機上所以串連時我使用以下語句。

 
串連代碼

$con = mysql_connect("localhost","root","");  //$con可理解為串連號

當然我們不能讓mysql一直處於串連狀態,對於小型應用來說或許這不算問題,但對於大型web應用來講這是很浪費資源的,所以用完資料庫連接之後我們要關掉它。這個任務我們交給mysql_close(串連號)來完成。


開啟和關閉資料庫連接

 代碼如下 複製代碼
$con = mysql_connect("loaclhost","root","");  
$con = mysql_close($con);  

 
 
弄明白了如何串連和斷開資料庫,接下來就是在mysql中建立資料庫,這聽起來很拗口,因為同一台mysql伺服器中可以允許多個資料庫的存在。這裡我們有兩種方法來建立資料庫,法一使用mysql_create_db()函數,但不建議大家使用這種方法。

 
建立資料庫

 代碼如下 複製代碼

$con = mysql_connect("localhost","root","");  
mysql_create_db("guestbook",$con);  
mysql_close($con);  

法二,我們直接採用mysql_query()函數來執行sql語句。Create DATABASE 就是用於建立資料庫的sql語句,例如Create DATABASE test,就是建立一個名為test的資料庫。
 

建立資料庫

 代碼如下 複製代碼

$con = mysql_connect("localhost","root","");    
mysql_query("Create DATABASE guestbook",$con);    
mysql_close($con);   

 

 建完資料庫,我們要向資料庫中添加資料表。同樣是採用mysql_query()函數來執行sql語句,但不同的是之前我們要使用mysql_select_db()函數來選擇我們操作的資料庫。

 代碼如下 複製代碼

$con = mysql_connect("localhost","root","");      
mysql_query("Create DATABASE guestbook",$con);  
mysql_select_db("guestbook",$con);  
mysql_query("Create TABLE users(username varchar(15), 
password varchar(15))");      
mysql_close($con);  
/*  建表語句: Create TABLE 表明(欄位名_1 欄位資料類型_1,欄位名_2 欄位資料類型_2,......,欄位名_n 欄位資料類型_n)      */ 

 


在資料庫中建立好表、欄位等資料資料關係之後,就差實實在在的資料了。同上,使用mysql_query()函數執行添加資料的sql語句,Insert INTO 表名 (欄位名_1,欄位名_2,......,欄位名_n) VALUES (資料_1,資料_2,......,資料_n)。

 代碼如下 複製代碼

 
$con = mysql_connect("localhost","root","");        
mysql_query("Create DATABASE guestbook",$con);    
mysql_select_db("guestbook",$con);    
mysql_query("Create TABLE users(username varchar(15),  
password varchar(15))");    
mysql_query("Insert INTO users (username,password) VALUES ('Ku_Andrew','123456')");      
mysql_close($con);   

現在,我們的資料庫中已經有了資料,接下來我們使用select語句來進去查詢。

 代碼如下 複製代碼
$con = mysql_connect("localhost","root","");        
mysql_query("Create DATABASE guestbook",$con);    
mysql_select_db("guestbook",$con);    
mysql_query("Create TABLE users(username varchar(15),  
password varchar(15))");   
$select = mysql_query("select * from users");  
while ($row = mysql_fetch_array($select);)  
{  
    echo $row['username'];  
    echo $row['password'];  
}  
mysql_close($con); 

  

這樣,通過while迴圈我們就可以把users表中所有的資料全部查詢出來,上面這樣做不好重複利了,下面我們可以做成資料庫連接類。

 代碼如下 複製代碼

<?php
//------------------------------------------------------------------------------------------
// ※Database()                   建構函式,資料庫初始參數
// ※Select()                     查詢
// ※GetRows()                    返回查詢的記錄總數
// ※Insert()                     插入記錄
// ※Update()                     更新
// ※Delete()                     刪除
// ※Halt()                       中斷並顯示錯誤資訊 111Cn.Net */
//------------------------------------------------------------------------------------------
define("DATABASETYPE", "1");       //定義資料庫類型:1為MySql;2為SQL Server;3為Oracle;4為Odbc
define("SERVER", "localhost");     //Host name or IP address of the database server
define("DATABASE", "dbName");   //要串連的資料庫名
define("USER", "tableName");     //用於串連資料庫的使用者名稱
define("PASSWORD", "paswd");    //用於串連資料庫的密碼 

class Database {
    var $dbLink;                      //串連控制代碼
    var $result;                      //查詢控制代碼
    var $insId;                       //Insert()成功返回AUTO_INCREMENT列的值
    var $rows;                        //返回資料數組
    var $numRows;                     //返回資料數目
    var $dbHost, $dbUser, $userPassword, $database;
    var $dbType = DATABASETYPE;
    var $msgFlag = "yes";            //yes:show the Mysql message ; no: die by show "Halted."

    function Database($dbHost = SERVER, $dbUser = USER, $userPassword = PASSWORD, $database = DATABASE) {
        switch ($this->dbType) {
            case 1:
                $this->dbLink = @mysql_pconnect($dbHost, $dbUser, $userPassword); // or die("Can't Connect to Remote Host!");
                @mysql_select_db($database, $this->dbLink); // or die ("Can't Connect to Remote Host!");
                break;
            case 2:
                break;
        }
        return true;
    }

    /* SQL:Select() 返回為false無結果 */

    function Select($table, $columns, $condition = 1) {
        $sql = "select $columns from $table where $condition ";
        $this->result = @mysql_query($sql, $this->dbLink);
        unset($this->rows);
        if ($this->result) {
            $i = 0;
            if (!($this->rows = array("$i" => @mysql_fetch_array($this->result))))
                return false;
            if (($this->numRows = @mysql_num_rows($this->result)) == 0)
                return false;
            while ($tempRows = @mysql_fetch_array($this->result)) {
                array_push($this->rows, $tempRows);
            }
        } else {
            $this->Halt($sql);
            return false;
        }
        return true;
    }

    /* SQL:GetRows() 返回查詢的記錄總數 */

    function GetRows($table, $condition = 1) {
        $sql = "select count(1) as count from $table where $condition";
        $this->result = @mysql_query($sql, $this->dbLink);
        if ($this->result) {
            $temp = @mysql_fetch_array($this->result);
            $this->numRows = $temp[count];
        } else {
            $this->Halt($sql);
            return false;
        }
        return $this->numRows;
    }

    /* SQL:Insert() */

    function Insert($table, $columns, $values) {
        $sql = "insert into $table ($columns) values ($values)";
        $this->result = @mysql_query($sql, $this->dbLink);
        if ($this->result)
            $this->insId = @mysql_insert_id($this->dbLink);
        else {
            $this->Halt($sql);
            return false;
        }
        return true;
    }

    /* SQL:Update() */

    function Update($table, $setings, $condition) {
        $sql = "update $table set $setings where $condition";
        $this->result = @mysql_query($sql, $this->dbLink);
        if ($this->result)
            $this->numRows = @mysql_affected_rows($this->result);
        else {
            $this->Halt($sql);
            return false;
        }
        return true;
    }

    /* SQL:Delete */

    function Delete($table, $condition) {
        $sql = "delete from $table where $condition";
        $this->result = @mysql_query($sql, $this->dbLink);
        if ($this->result)
            $this->numRows = @mysql_affected_rows($this->result);
        else {
            $this->Halt($sql);
            return false;
        }
        return true;
    }

    /* Halt():error message */

    function Halt($msg) {
        if ($this->msgFlag == "yes") {
            printf("<b>Database Query Error:</b> %s<br>n", $msg);
            printf("<b>MySql Error:</b> %s<br>n", mysql_error());
        }else
            echo "<META HTTP-EQUIV=REFRESH CONTENT='0;URL=../include/error.htm'>"; //自定一個出錯提示檔案
        return false;
    }
}

switch ($db->dbType) {
    case 1:
        @mysql_close();
        break;
    case 2:
        break;
}
$db = new Database();
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.