<?php
// Class for a DB object
class MyDB extends SQLite3 {
    function __construct($dbname) {
        $this->open($dbname);
    }
}

// Open the DB (create the object)
$db = new MyDB('../../Issues/issuesdb');

// Pick up the where clause from the form and check for maliciousness.
$where = $_POST['where'];
if (preg_match('/;|"|insert|drop|join|alter|delete|select|update|where/i', $where)) {
    echo "<html><head><meta http-equiv=\"refresh\" content=\"0;URL='query.html'\" />";
    exit;
}

// Build the query
$sql = "select * from Issues where Subject like '%$where%'";
echo "<br>$sql<br>";

// Execute the query
$result = $db->query($sql);

// Is there a result? Yes process it otherwise an error message.
if ($result) {

    echo "<table border=\"2px\"><tr>";

    // Get and display the field names (header) for the result as a table
    $columns = $result->numColumns();
    for($i = 0; $i < $columns; $i++) {
        $fields[$i] = $result->columnName($i);
        echo "<td><b><center>$fields[$i]<center><b></td>";
    }
    echo "</tr>";

    // Fetch rows of the result indexed by field name and display
    while($row = $result->fetchArray(SQLITE3_ASSOC) ) {
        $outval = "";
        echo "<tr>";
        foreach($fields as $field ) {
            // If Link then display it as a link.
            if ($field == "Link") {
                $outval = $outval . "<td><a href=\"$row[$field]\" target=\"_blank\">$row[$field]</a></td>";
            }else{
                $outval = $outval . "<td>$row[$field]</td>";
            }
        }
        echo $outval;
        echo "</tr>";
    }
    echo "</table>";
    }else{
    echo "<b>No results!</b>";
}