[英]retrieve variable from another php file
我想显示查询的输出,但是我不能检索变量$ result,主要是因为它在不同的文件中,但是我用require来获取它,但是我仍然得到未定义的错误变量,我想知道如何我检索到function.php上的$ result,并在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!");
}
为了扩展Arron W.的注释,在您的function.php文件中,您将需要返回$ result,然后在search.php中,您将使用return装入变量,然后使用该变量来访问数据。
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()){
}
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.