我想显示查询的输出,但我无法检索我的变量$ result主要是因为它在不同的文件但我使用require来获取它但我仍然得到未定义的错误变量,我想知道如何检索在function.php上的$结果并在search.php上使用它来显示。
的search.php
<?php
include "db.php";
include "function.php";
if(isset($_GET['keywords'])){
global $connection;
$keyword = ($_GET['keywords']);
searchData($keyword);
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="search.php" method="GET">
<label>
Search
<input type="text" name="keywords">
</label>
<input type="submit" name="search">
<div class="form-group">
<div class="result-count">
Found <?php echo $query->num_rows; ?>result
</div>
<?php
if($query->num_rows){
while($r = $query->fetch_rows()){
}
}
?>
</div>
</form>
</body>
</html>
function.php
<?php require_once "db.php";?>
<?php
function searchData($keyword){
global $connection;
$query = ("
SELECT username
FROM users
WHERE username LIKE '%{$keyword}%'
");
$result = mysqli_query($connection, $query);
echo "$result->num_rows". "found";
}
?>
db.php中
<?php
$connection = new mysqli('localhost', 'root', '',
'loginapp');
if(!isset($connection)){
die("Database connection failed!");
}
答案 0 :(得分:1)
要扩展Arron W。的评论,在你的function.php文件中,你需要返回$ result,然后在search.php中你将使用load返回变量,然后使用该变量访问数据。
function.php
$result = mysqli_query($connection, $query);
echo "$result->num_rows". "found";
return $result
}
?>
的search.php
if(isset($_GET['keywords'])){
global $connection;
$keyword = ($_GET['keywords']);
$result = searchData($keyword);
}
...
<div class="result-count">
Found <?php echo $result->num_rows; ?>result
</div>
<?php
if($result->num_rows){
while($r = $result->fetch_row()){
}
}
?>