使用MYSQL和PHP搜索HTML表单

0 html php mysql mysqli

在我的数据库上执行一个简单的PHP/SQL搜索栏,结果不会出现.出现搜索栏,我输入的任何内容都没有出现在URL中.代码如下.我通过不同的文件连接到数据库.

的index.php

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <center>    		
        <form action="search.php" method="post">
		<input type="text" name="search" autocomplete="off">
        	<input type="submit" value="search">
        </form>
    </center>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

search.php中

<?php
	$search = $_GET['search'];
	require 'constants.php';
?>

<?php

$query = "SELECT Name, Zip, Address, Type FROM parks WHERE Zip = '%{$search}%'";

$result = mysqli_query($db_connection,$query);

while ($row = mysqli_fetch_array($result))
{
    // loop through output one row at a time
    $name = 		$row["Name"];
    $zip = 		$row["Zip"];
    $address = 		$row["Address";
    $type = 	$row["Type"];

    echo $name . $zip . $address . $type;
}

?>
Run Code Online (Sandbox Code Playgroud)

Kev*_*vin 7

首先,您明确将方法类型设置为POST:

<form action="search.php" method="post">
Run Code Online (Sandbox Code Playgroud)

然后,你试图获得以下值:

<input type="text" name="search" autocomplete="off">
Run Code Online (Sandbox Code Playgroud)

通过$search = $_GET['search'];.使用$_POST['search'];

其次,这没有意义

WHERE Zip = '%{$search}%'";
Run Code Online (Sandbox Code Playgroud)

如果要使用通配符进行搜索,请使用更好的LIKE子句.

为什么不使用准备好的陈述:

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

if(isset($_POST['search'])) {
    require 'constants.php';
    $search = '%' . $_POST['search'] . '%';
    $query = "SELECT Name, Zip, Address, Type FROM parks WHERE Zip LIKE ?";

    $select = $db_connection->prepare($query);
    $select->bind_param('s', $search);
    $select->execute();
    $select->store_result();

    if($select->num_rows > 0) {
        $select->bind_result($name, $zip, $address, $type);
        while($select->fetch()) {
            // loop through output one row at a time

            echo $name . $zip . $address . $type . '<br/>';
        }
    }

}
?>
Run Code Online (Sandbox Code Playgroud)

获取的另一种方式:

if(isset($_POST['search'])) {
    require 'constants.php';
    $search = '%' . $_POST['search'] . '%';
    $query = "SELECT Name, Zip, Address, Type FROM parks WHERE Zip LIKE ?";

    $select = $db_connection->prepare($query);
    $select->bind_param('s', $search);
    $select->execute();
    $results = $select->get_result();

    if($select->num_rows > 0) {
        while($row = mysqli_fetch_assoc($results)) {
            // loop through output one row at a time
            $name = $row["Name"];
            $zip = $row["Zip"];
            $address = $row["Address"];
            $type = $row["Type"];

            echo $name . $zip . $address . $type . '<br/>';
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @JoshuaMobley确保您的错误报告已打开,我做了一些修改,看一看 (2认同)