我的页面有一个搜索表单,我从 index.php 运行,通过调用 function.php 中的搜索功能并与setup.php建立连接。
搜索字段显示正常,并且没有数据库连接错误。然而,弹出的错误是:index.php()中的Notice: Undefined variable: search_results
。确切的行是它在表单下方显示的位置:<?php if ( $search_results ) : ?>
。我认为这是因为 $ search_results 未在第一个if
语句中声明为全局。但在将其全局化后,错误仍然存在。
非常感谢任何有关错误原因的见解。
index.php的内容:
<?php require_once ('setup.php');
require_once ('function.php');
?>
<!DOCTYPE html>
<html>
<body>
<?php
if ( isset( $_GET['s'] ) ) {
global $search_results;
$search_term = htmlspecialchars($_GET['s'], ENT_QUOTES);
$search_results = search($conn, $search_term);
}
?>
<form role="search" method="get" class="search-form" action="">
<label>
<input type="search" class="search-field" placeholder="Search" value="searchitem" name="s"
title="Search after:">
</label>
<input type="submit" class="search-submit" value="Search">
</form>
<?php if ( $search_results ) : ?>
<div class="results-count">
<p><?php echo $search_results['count']; ?> results found</p>
</div>
<div class="results-table">
<?php foreach ( $search_results['results'] as $search_result ) : ?>
<div class="result">
<p><?php echo $search_result->title; ?></p>
</div>
<?php endforeach; ?>
</div>
<div class="search-raw">
<pre><?php print_r($search_results); ?></pre>
</div>
<?php endif; ?>
<body>
</html>
Function.php :
<?php
function search($conn, $search_term) {
$sanitized = $conn->mysqli->real_escape_string($search_term);
$query = $conn->mysqli->query("
SELECT *
FROM news
WHERE title LIKE '%{$sanitized}%'
OR body LIKE '%{$sanitized}%'
OR sources LIKE '%{$sanitized}%'
OR date LIKE '%{$sanitized}%'
");
if ( ! $query->num_rows ) {
return false;
}
while( $row = $query->fetch_object() ) {
$rows[] = $row;
}
$search_results = array(
'count' => $query->num_rows,
'results' => $rows,
);
return $search_results;
}
?>
Setup.php:
<?php
$hn = 'localhost';
$db = 'boh';
$un = 'water';
$pw = 'water';
#DB Connection:
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
?>
正如回复中所建议的,我尝试了if ( isset($search_results ))
,这样就摆脱了错误,但是当我运行搜索(点击按钮)时,出现了以下错误:
Notice: Undefined property: mysqli::$mysqli in C:\xampp\htdocs\form\function.php on line 4
Fatal error: Call to a member function real_escape_string() on null in C:\xampp\htdocs\form\function.php on line 4
第4行:$ sanitized = $ conn-&gt; mysqli-&gt; real_escape_string($ search_term);