<?php
// Reflected XSS + SQLi on `q` and `id`.
$dbh = @new mysqli(getenv('DB_HOST') ?: 'db', 'root', getenv('DB_PASS') ?: 'toor', getenv('DB_NAME') ?: 'newploit');

$q    = $_GET['q']    ?? '';
$cat  = $_GET['cat']  ?? '';
$sort = $_GET['sort'] ?? 'id';

$sql = "SELECT id, name, price, description FROM products WHERE name LIKE '%$q%'";
if ($cat !== '') $sql .= " AND category='$cat'";
$sql .= " ORDER BY $sort";

$rows = [];
$err = '';
if ($dbh && !$dbh->connect_errno) {
    $res = @$dbh->query($sql);
    if ($res === false) {
        $err = $dbh->error;
    } else {
        while ($r = $res->fetch_assoc()) $rows[] = $r;
    }
}
?><!DOCTYPE html>
<html><body>
<h1>Search results for: <?= $q /* XSS: reflected unescaped */ ?></h1>

<form method="get">
    <input name="q" value="<?= $q ?>" placeholder="search">
    <input name="cat" value="<?= $cat ?>" placeholder="category">
    <button>go</button>
</form>

<?php if ($err): ?>
<pre style="color:red">SQL error: <?= $err ?>
Query: <?= htmlspecialchars($sql) ?></pre>
<?php endif; ?>

<table border=1>
<tr><th>id</th><th>name</th><th>price</th><th>description</th></tr>
<?php foreach ($rows as $r): ?>
<tr>
    <td><?= $r['id'] ?></td>
    <td><?= $r['name'] ?></td>
    <td><?= $r['price'] ?></td>
    <td><?= $r['description'] ?></td>
</tr>
<?php endforeach; ?>
</table>

<p><?= count($rows) ?> result(s)</p>
</body></html>
