我是mysqli的新手,只是熟悉一些php。我正在做一个教程,并在我的代码中遇到了这个错误。致命错误:未捕获错误:在Search.php中调用null上的成员函数search():19堆栈跟踪:#0 {main}。任何人都可以解释我正在寻找什么来纠正这个错误?它确实连接到数据库我刚刚更改了底部连接信息以用于在线目的。
这是我的search.php及其下面的代码 - class-search.php
<?php
$search_results="";
//Check if search data was submitted
if ( isset( $_GET['s'])){
//Include the search class
require( dirname(_FILE_) . '/classes/class-search.php');
//Instantiate a new instance of search class
$search_term - new search();
//Store search term into a variable
$search_term = $_GET['s'];
//Send the search term to our search class and store result
$search_results = $search->search($search_term);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
</head>
<body>
<h1>Search</h1>
<div class="search-form">
<form action="" method="GET">
<div class="form-field">
<label for="search-field">Search</label>
<input type="search" name="s" placeholder="Enter your search term" results="5" value="<?php echo
$search_term; ?>">
<input type="submit" value="Search">
</div>
</form>
</div>
<?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->name; ?></p>
</div>
<?php endforeach; ?>
</div>
<div class="search-raw">
<pre><?php print_r($search_results); ?></pre>
</div>
<?php endif; ?>
</body>
</html>
以下是class-search.php的代码
<?php
class search{
//mysqli connection
private $mysqli;
//constructure that sets up the class
public function __construct() {
//Connect to our database and store in $mysqli property
$this->connect();
}
//Database connection ths connects to our database
private function connect() {
$this->mysqli = new mysqli( '$host_name', '$user_name', '$password', '$database );
//Performs the search
public function search($search_term){
//sanitizes the search term to prevent injection attacks
$sanitized = $this->mysqli->real_escape_string($search_term);
//run the query
$query = $this->mysqli->query("SELECT name FROM Simple WHERE name LIKE '{$sanitized}%'");
//Check Results
if( ! $query->num_rows) {
return false;
}
//Loop and fetch data
while( $row = $query->fetch_object() ){
$rows[] =$row;
}
//Build and return results
$search_results = array(
'count'=> $query->num_rows,
'results' => $rows,
);
return $search_results;
}
}
?>