无法在数据库中搜索特定记录

时间:2018-03-21 06:37:38

标签: php html search phpmyadmin

我想在数据库中搜索特定记录并在html页面上显示。我插入了一个带搜索按钮的搜索栏。我想输入让我们说学生姓名并在html表格中查看该学生的记录。但它不起作用,它在表格中没有显示任何内容。以下是搜索代码:



<?php
include("connection.php");
if (isset($_POST['search'])) {
	$valueToSearch=$_POST['valueToSearch'];
	$query="SELECT * FROM 'table_name' WHERE Student_Name LIKE '%".$valueToSearch."%";
	$search_result=filterTable($query);

}
else{
	$query="SELECT * FROM 'table_name'";
	$search_result=filterTable($query);
}
function filterTable($query)
{
	$connect=@mysql_connect("localhost","root","","db");
	$filter_Result=@mysql_query($connect,$query);
	return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
	<title>Search Record</title>
	<style>
	table,tr,th,td
	{
		border:1px solid black;
	}
</style>
</head>
<body>
	<form action="search.php" method="post">
		<input type="text" name="valueToSearch" placeholder="ValueToSearch"><br><br>
		<input type="submit" name="search" value="Filter"><br><br>
		<table>
     <tr>
                    <th>Id</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Age</th>
                </tr>
                <?php while($row = mysqli_fetch_array($search_result)):?>
                <tr>
                    <td><?php echo $row['id'];?></td>
                    <td><?php echo $row['fname'];?></td>
                    <td><?php echo $row['lname'];?></td>
                    <td><?php echo $row['age'];?></td>
                </tr>
                <?php endwhile;?>
            </table>
        </form>
        
    </body>
</html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

使用mysql_escape_string();转义关键字,就像第二件事一样,使用mysql*使用mysqlipdo,因为mysql*已从{{1}中移除}}

php 7.*

之后使用此查询

$valueToSearch= mysqli_real_escape_string($connect,$_POST['valueToSearch']);

因为你有回音的语法错误,你需要得到这样的

$query="SELECT * FROM table_name WHERE Student_Name LIKE '%$valueToSearch%'";

我举例SELECT * FROM table_name WHERE Student_Name LIKE 'something'; 将其粘贴到mysqli

connection.php

现在你的代码应该是

$connect=mysqli_connect("localhost","root","","db");

答案 1 :(得分:0)

忘记任何mysql_功能。您正在使用mysql建立与数据库的连接,但尝试使用mysqli_读取结果。尝试使用

<?php
include("connection.php");
if (isset($_POST['search'])) {
    $valueToSearch=$_POST['valueToSearch'];
    $query="SELECT * FROM 'table_name' WHERE Student_Name LIKE '%".$valueToSearch."%'";

    $search_result=filterTable($query);

}
else{
    $query="SELECT * FROM 'table_name'";
    $search_result=filterTable($query);
}
function filterTable($query) {
    $connection = new mysqli("localhost", "root", "","db");
    $filter_Result = $connection->query($query)
    return !$filter_Result ? null : $filter_Result;
}
?>

然后,在您的表单中,替换:

while ($row = $search_result->fetch_array()) {
    ...
    ...
}

提示:

  • 考虑将连接建立从filterTable()函数移动到connection.php文件并在函数中使用GLOBAL $connection;
  • 将您的连接移动到该文件将允许您随时使用$myVar = $mysqli->real_escape_string( $myVar )转义字符串,这将阻止注入