<?php

// Do we have a search query?
if (!isset ($_GET['q']))
    exit ();

// Truncate
$query = substr (trim ($_GET['q']), 0, 2048);

// Empty search?
if (strlen ($query) == 0)
    exit ();

// Search SQLite for a topic
$nodes_db = new PDO ('sqlite:nodes.sqlite');

$stmt = $nodes_db->prepare (
    'SELECT * ' .
    'FROM `node`' .
    'WHERE LOWER(`name`) LIKE LOWER(?)' .
    'LIMIT 50');

$stmt->execute ([ $query . '%' ]);

$result = $stmt->fetchAll (PDO::FETCH_ASSOC);

// Return results as formatted HTML

foreach ($result as $a_result)
{
    echo    '<a href="/search?q=' . rawurlencode ($a_result['name']) . '">' .
                '<strong>' .
                    htmlspecialchars (substr ($a_result['name'], 0, strlen ($query))) .
                '</strong>' .
                htmlspecialchars (substr ($a_result['name'], strlen ($query))) .
            '</a>';
}
