Reputation: 181
i wanted to display the output of the query, but i cant retrieve my variable $result mainly because it is on a different file but i used the require to get it but i still get the error variable not defined,i wanted to know how can i retrieve the $result that's been on function.php and used it on the search.php to display.
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!");
}
Upvotes: 0
Views: 255
Reputation: 66
To expand on Arron W.'s comment, In your function.php file, you will need to return $result, then in search.php you will use load the return into a variable, then use that variable to access the data.
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()){
}
}
?>
Upvotes: 1