1. 程式人生 > >PHP 和 ajax (三),操作mysql

PHP 和 ajax (三),操作mysql

   php通過ajax讀取mysql表中的資料,涉及到三個頁面:html頁面,js頁面,php頁面。

完整的內容請看:https://github.com/hefrankeleyn/learning-area/tree/master/003PHP/php-ajax

一、html頁面

<body>
    <p>
        <span>Select a User:</span>
        <select name="users" id="users">
            <option value="1">Peter Griffin</option>
            <option value="2">Lois Griffin</option>
            <option value="3">Joseph Swanson</option>
            <option value="4">Glenn Quagmire</option>
        </select>
    </p>
    <p>
        <div: id="txtHint"><b>User info will be listed here.</b></div:>
    </p>
    <script src="mysqlUser.js"></script>
</body>

二、js頁面,mysqlUser.js

(function(){
    var cds = document.getElementById("users")
    cds.removeEventListener("change",function(){
        showCD(cds.value);
    });
    cds.addEventListener("change",function(){
        showCD(cds.value);
    });

    var xmlHttp;
    function showCD(str){
        xmlHttp = GetXmlHttpRequestObject();
        if(xmlHttp === null){
            console.log("Browser does not support Http request.");
            return;
        }
        xmlHttp.onreadystatechange = stateChanged;
        var url = generateUrl("mysqlUser.php",str);
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    }
    // ajax 請求成功,進行的操作
    function stateChanged(){
        if(xmlHttp.readyState==4 || xmlHttp.readyState == "complete"){
            var txtHint = document.getElementById("txtHint")
            txtHint.innerHTML = xmlHttp.responseText;
        }
    }
    // 拼接url,拼接一個隨機數,防止使用快取
    function generateUrl(php_path,str){
        var url = php_path+"?q="+str;
        url += "&sid="+Math.random();
        return url;
    }
    // 獲取xmlRequestObject
    function GetXmlHttpRequestObject(){
        var xmlHttp=null;
        try{
            // Fire,Opera 8+, Safari
            xmlHttp = new XMLHttpRequest();
        }catch(e){
            // Internet Explorer
            try{
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            }catch(e){
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        return xmlHttp;
    }
})();

三、php頁面,mysqlUser.php

<?php
    // 建立mysql資料庫連線
    function getMysqli($ip,$username,$password,$database){
        $mysqli = new mysqli($ip,$username,$password,$database);
        if($mysqli->connect_errno){
            echo "Failed to connect (".$mysqli->connect_errno."), ".$mysqli->connect_error;
            return "error";
        }
        return $mysqli;
    }
   function selectUsersByid($id){
        $select_str = "select uid,firstname,lastname,age,hometown,job
                       from users where uid=$id";
        // 建立mysqli
        $mysqli = getMysqli($GLOBALS['ip'],$GLOBALS['username'],$GLOBALS['password'],$GLOBALS['database']);
        $select_res = $mysqli->query($select_str);
        if(!$select_res){
            echo echoError($mysqli);
            return;
        }
        // 遍歷 查詢結果
        for($row_num=0;$row_num<$select_res->num_rows;$row_num++){
            $select_res->data_seek($row_num);
            $rows = $select_res->fetch_assoc();
            foreach($rows as $key=>$value){
                echo "$key : $value <br>";
            }
            echo "*******";
        }
        $mysqli->close();
    }

    $id = $_GET["q"];
    selectUsersByid($id);
?>