How to query the SQLITE database from an HTML script

advertisements

What's the write syntax to query an SQLITE database from inside an HTML script? The code below (which btw works perfectly when used in a separate php file) doesn't return anything in the textarea....

Any help would be highly appreciated. Thanks

<p>Patient search:</p>
<textarea id="SearchBoxPt" textarea name="SearchBoxPt" style="height: 30px; resize: none; width: 600px;">
</textarea></p> 

<button type="button" onclick="populateField_SearchPt()">Load Pt 1</button>

<script>
function populateField_SearchPt()
{
    <?php
    class MyDB extends SQLite3
    {
        function __construct()
        {
            $this->open('Anagrafica.db');
        }
    }

    $db = new MyDB();
    if(!$db)
    {
        echo $db->lastErrorMsg();
    } else
    {
        echo "Opened database successfully\n\n";
    }

    $results = $db->query('SELECT name FROM Anagrafica WHERE hospital_ID="1"');
    ?>    

    document.getElementById ("SearchBoxPt").value = $results;
}
</script>


Here is an example

PHP

<?php
class MyDB extends SQLite3
{
    function __construct()
    {
        $this->open('Anagrafica.db');
    }
}

$db = new MyDB();
if(!$db)
{
    echo $db->lastErrorMsg();
}

$hId = $_GET['hId']; //we're getting the passed hId as a paramater in the url

$query = $db->prepare("SELECT name FROM Anagrafica WHERE hospital_ID=:id");
$query->bindValue(':id', $hId, SQLITE3_INTEGER);
$results = $query->execute()->fetchArray();
echo $results['name'];
?>

HTML

<p>Enter Hospital Id:
    <input id="HospitalId" type="number" value="1">
</p>

<p>Patient search:</p>
<textarea id="SearchBoxPt" textarea name="SearchBoxPt" style="height: 30px; resize: none; width: 600px;">
</textarea>
</p> 

<button type="button" onclick="populateField_SearchPt()">Load Pt 1</button>

<script>
function populateField_SearchPt()
{
    var inputId = document.getElementById("HospitalId").value; //we get the user input value and put it in a var

    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "path/to/yourPhpFile.php?hId=" + inputId, true); // we're passing the hId to the server as a parameter
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("SearchBoxPt").value = this.responseText;
        }
    };
    xhttp.send(); 

}
</script>