Pages

Friday, March 18, 2011

PHP - Using SQLite3

/**
 * index.php
 */

<html>
<head>
<script src="jquery.js"></script>
<script>
function save(){
    var ajax = new XMLHttpRequest();
    var name = document.getElementById('name');
    var city = document.getElementById('city');
    var age = document.getElementById('age');
    var mode = 'write';
    


    ajax.open("GET", "hello.php?name="+name.value+"&city="+city.value+"&age="+age.value+"&mode="+mode, false);
    ajax.send();
   
    $response = ajax.responseText;
   
    if($response == "okey"){
        $('#msg').text('Successfully Saved');
    }else{
        $('#msg').text('Failure to save');
    }
   
}

function look(){
    var ajax = new XMLHttpRequest();
    ajax.open('GET','hello.php?mode=read',false);
    ajax.send();
    var res = ajax.responseText;
    res = res.replace('&gt;','>');
    res = res.replace('&lt;','<');
    $('#data').html(res);
}
</script>
</head>
<body>
    <div id="form">
        <p id="msg"></p>
        <table>
            <tr><td>Name</td><td>:</td><td><input type="text" id="name"/></td></tr>
            <tr><td>City</td><td>:</td><td><input type="text" id="city"/></td></tr>
            <tr><td>Age</td><td>:</td><td><select id="age">
                <?php
                    $output = '';
                    for($i=21; $i< 60; $i++){
                        $output .= '<option value='.$i.'>'.$i.'</option>';
                    }
                    echo $output;
                ?>
                </select></td></tr>
            <tr><td>&nbsp;</td><td>&nbsp;</td><td><input type="button" onclick="save()" value="Save"/></td></tr>
        </table>
        <hr/>
        <p><input type="button" value="Look Up" onclick="look()"/></p>
        <div id="data"></div>
       
    </div>
</body>
</html>



/**
 * hello.php
 */

<?php

$name = $_GET['name'];
$city = $_GET['city'];
$age = $_GET['age'];
$mode = $_GET['mode'];

$sql = new SQLite3("lola.db");
   
if(strcmp($mode,"write") == 0){
    $sql->exec("INSERT INTO hello VALUES ('$name','$city',$age)");
    echo "okey";
}else if(strcmp($mode,"read") == 0){
    $result = $sql->query("SELECT * FROM hello");
    $output = '<table><tr><th>No</th><th>Name</th><th>City</th><th>Age</th></tr>';
    $i = 1;
    while($row = $result->fetchArray()){
        $output .= '<tr>';
        $output .= '<td>'.$i++.'</td>';
        $output .= '<td>'.$row['name'].'</td>';
        $output .= '<td>'.$row['city'].'</td>';
        $output .= '<td>'.$row['age'].'<td>';
        $output .= '</tr>';
    }
    $output .= '</table>';
   
    echo $output;
}



No comments:

Post a Comment