简体   繁体   English

通配符搜索 MySQL 中的单个文本字段和 HTML 页面上的 PHP

[英]Wildcard searching single text field in MySQL with PHP on HTML page

I've inherited some PHP scripts from a colleague and one is used for searching the "Notes" text field of a database called "Sheep" via a text box:我从同事那里继承了一些 PHP 脚本,其中一个用于通过文本框搜索名为“Sheep”的数据库的“Notes”文本字段:

文本搜索框

Code for the search box:搜索框代码:

<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">

However when anything is searched it currently shows the following error:但是,当搜索任何内容时,它当前显示以下错误:

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.

I don't know PHP well at all but below is the PHP code.我根本不知道 PHP 但下面是 PHP 代码。 All I know is that it needs to be able to search the text field called "Notes" for any string of text using the wildcard syntax:我所知道的是,它需要能够使用通配符语法在名为“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();
  }
}
?>

Can anyone advise where this is wrong?谁能告诉我哪里错了? I've done some research but after many attempts at fixing it I've not been able to.我做了一些研究,但经过多次尝试修复后我一直无法修复。

You should replace $notes in the query with :sheep .您应该将查询中的$notes替换为:sheep Then concatenate the wildcard characters to to $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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM