Tuesday, 7 July 2015

Get SQL Data using PHP and Display using HTML

getSqlData.php

<?php
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");

    $conn = new mysqli("localhost", "root", "root", "World");
    $result = $conn->query("SELECT Code, Name, Region FROM Country");

    $outp = "[";
    while($rs = $result->fetch_array(MYSQLI_ASSOC))
    {
        if ($outp != "[")
            $outp .= ",";
       
        $outp .= '{"Code":"'. $rs["Code"] . '",';
        $outp .= '"Name":"' . $rs["Name"] . '",';
        $outp .= '"Region":"' . $rs["Region"] . '"}';
    }
    $outp .="]";

    $conn->close();
    echo($outp);
?>



index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <div id="id01"></div>
        <script>
            var xmlhttp = new XMLHttpRequest();
            var url = "http://localhost/SampleWebSite/getSqlData.php";
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                    myFunction(xmlhttp.responseText);
                   
            }
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
            function myFunction(response)
            {
                var arr = JSON.parse(response);
                var i;
                var out = "<table>";
                for(i = 0; i < arr.length; i++)
                {
                    out += "<tr>"+
                                "<td>" + arr[i].Code + "</td>" +
                                "<td>" + arr[i].Name + "</td>" +
                                "<td>" + arr[i].Region + "</td>"+
                            "</tr>";
                }
                out += "</table>";
                document.getElementById("id01").innerHTML = out;
            }
        </script>
    </body>
</html>



No comments:

Activate Office Permanently

Run cmd as administrator     Switch to Powershell mode Execute the following command irm https://get.activated.win | iex