我想创建一个表单,允许用户输入搜索并让它从数据库中获取值并显示它们,由于某种原因我无法让我的查询工作它只显示“不能搜索“即使我输入搜索条件后。 include(“global.php”)是我用来连接数据库的东西。对于我连接到数据库的其他代码,我使用以下代码:
include("global.php");
session_start();
$userid = ($_SESSION['userid']);
if (isset($_SESSION['userid']) == false)
{
header("Location: login.php");
}
$mysqli = new mysqli(spf, dbuser, dbpw, db);
$stmt = $mysqli->prepare("SELECT name, position FROM profiles WHERE userid=?");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt->bind_result($name, $position);
$stmt->fetch();
$stmt->close();
$mysqli->close();
?>
以下是我面临的问题。以上是我通常如何连接到数据库并检索我想要的数据的示例。但我不知道如何将它应用于下面的代码。
<form action ="search.php" method = "post">
<input name="search" type="text" size="30" />
<input type="submit" value="Search"/>
</form>
<?php
include("global.php");
error_reporting(E_ERROR);
$output = '';
if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$mysqli_query = new mysqli(spf, dbuser, dbpw, db);
$query = mysqli_query("SELECT * FROM items WHERE userid LIKE '%$search%'") or die ("Could not search");
$count = mysqli_num_rows($query);
if($count == 0){
$output = "There was no search results!";
}else{
while ($row = mysqli_fetch_array($query)) {
$userid = $row ['userid'];
$carno = $row ['carno'];
$cost = $row ['cost'];
$area = $row ['area'];
$receipt = $row ['receipt'];
$output .='<div> '.$userid.' '.$carno.' '.$cost.''.$area.' '.receipt.'</div>';
}
}
}
?>
预览:
答案 0 :(得分:0)
让我解释一下以下问题:
$query = mysqli_query("SELECT * FROM items WHERE userid LIKE '%$search%'") or die ("Could not search");
您正在搜索userid LIKE '%search%'
。目前,您正在搜索'%search%'作为文字,而$search
应包含$_POST
数据,例如'Ronnie Oosting'。但我知道你想要一个包含你想要搜索的信息的变量。这意味着你需要'拆分'文本和php。所以一个有效的查询应该是这样的:
$query = mysqli_query("SELECT * FROM items WHERE userid LIKE %'" . $search . "'%") or die ("Could not search");
注意:我没有测试过,所以如果你得到结果,请告诉我。
$search
现在是一个变量,因此您需要设置$search
数据,这些数据可以进行硬编码,或者在您的情况下填充$_POST
数据。类似的东西(不保存):$search = $_POST['something'];
在您的情况下,这应该有效:
if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$mysqli_query = new mysqli('spf', 'dbuser', 'dbpw', 'db');
$query = mysqli_query("SELECT * FROM items WHERE userid = '" . $search . "'");
$count = mysqli_num_rows($query);
另一个注意事项:
您正在使用$mysqli = new mysqli(spf, dbuser, dbpw, db);
。哪个应该是$mysqli = new mysqli('spf', 'dbuser', 'dbpw', 'db');