@ PHP

CRUD:レコードの検索

フォームから送信された値から SQL を組み立てて、書名を部分一致条件で検索します。

search.php

<!DOCTYPE html>
<html lang="ja">

<head>
  <title>PHP PDO CRUD</title>
  <link rel="stylesheet" href="styles.css">
</head>

<body>

<main class="container">
<h1>product_search</h1>
  <form action="" method="post" name="form1" id="form1">
    <fieldset>
      <div>
        <input type="text" name="name">
      </div>
      <div>
        <p>
          <a href="javascript:document.form1.submit()">検索</a>
        </p>
      </div>
    </fieldset>
  </form>
  <table>
    <tr>
      <th>id</th>
      <th>品名</th>
      <th>価格</th>
    </tr>
<?php require_once('dbconnect.php') ?>
<?php
$sql = <<<SQL
SELECT * FROM products
SQL;

if (isset($_POST['name'])) {
    $fstr = $_POST['name'];
    if ($fstr != '') {
        $sql .= " WHERE name LIKE '%$fstr%'";
    }
}

try {

    $stmt = $dbh->query($sql);

    while ($row = $stmt->fetch()) {
        $id = $row['id'];
        $name = $row['name'];
        $price = $row['price'];
        print <<<EOD
    <tr>
      <td>$id</td>
      <td>$name</td>
      <td>$price</td>
    </tr>\n
EOD;
    }
} catch (PDOException $e) {
    print "ERR! : {$e->getMessage()}";
} finally {
    $dbh = null;
}
?>
  </table>
</main>

</body>
</html>