在HTML页面上使用PHP在MySQL中搜索单个文本字段

e37o9pze  于 2023-01-24  发布在  PHP
关注(0)|答案(1)|浏览(118)

我从同事那里继承了一些PHP脚本,其中一个用于通过文本框搜索名为“Sheep”的数据库的“Notes”文本字段:

搜索框的代码:

<h2>Find sheep Notes</h2>

Please note this looks at both sheeps and lambs.

    <form method="post">
        <label for="sheep"><br>Enter text in the box</label>
        <input type="text" id="sheep" name="sheep">
        <input type="submit" name="submit" value="View Results">

但是,当搜索任何内容时,当前显示以下错误:

SELECT *, DATE_FORMAT(DOB, '%d-%m-%Y') AS DOB, DATE_FORMAT(`Record started Date`, '%d-%m-%Y') AS `Record started Date`, FROM Sheep, WHERE `Notes` LIKE '%section%'
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
No results found for section.

我对PHP一点都不了解,但下面是PHP代码,我所知道的是它需要能够使用通配符语法搜索名为“Notes”的文本字段中的任何文本字符串:

<?php

//error_reporting(-1);
//ini_set('display_errors', 'On');

if (isset($_POST['submit'])) {
  try {
    require "./config.php";
    require "./common.php";

    $connection = new PDO($dsn, $username, $password, $options);
$notes = $_POST['sheep'];
    $sql = "SELECT *,
DATE_FORMAT(DOB, '%d-%m-%Y') AS DOB,
DATE_FORMAT(`Record started Date`, '%d-%m-%Y') AS `Record started Date`
FROM Sheep
WHERE `Notes` LIKE '%$notes%'";

    $sheep = $_POST['sheep'];

    $statement = $connection->prepare($sql);
    $statement->bindParam(':sheep', $sheep, PDO::PARAM_STR);
    $statement->execute();

    $result = $statement->fetchAll();
  } catch(PDOException $error) {
    echo $sql . "<br>" . $error->getMessage();
  }
}
?>

有人能告诉我这是哪里错了吗?我做了一些研究,但经过多次尝试,我一直无法修复它。

bzzcjhmw

bzzcjhmw1#

您应该将查询中的$notes替换为:sheep。然后将通配符连接到$sheep

$connection = new PDO($dsn, $username, $password, $options);
    $sql = "SELECT *,
DATE_FORMAT(DOB, '%d-%m-%Y') AS DOB,
DATE_FORMAT(`Record started Date`, '%d-%m-%Y') AS `Record started Date`
FROM Sheep
WHERE `Notes` LIKE :sheep";

    $sheep = '%' . $_POST['sheep']. '%';

    $statement = $connection->prepare($sql);
    $statement->bindParam(':sheep', $sheep, PDO::PARAM_STR);
    $statement->execute();

相关问题