Jump to content

search script not working


peppericious

Recommended Posts

I'm getting a blank screen when I run the following search script. The script should retrieve news entries from the db which contain the keyword and echo those entries with the keyword highlighted in yellow.

 

Could anyone shed light on why the script isn't running as it should?...

 

Thanks in advance if you can help.

 

<?php 
if($_SERVER['REQUEST_METHOD'] == 'POST') { // form submitted
  if(!empty($_POST['keywords'])) { // search term has been entered
		$keywords = trim($_POST['keywords']);
		$search_exploded = explode(" ", $keywords);
		include('includes/mysqli_connect.php'); // connect to db
		// execute query
		$q = "SELECT title, subtitle, news_entry
		FROM news
		WHERE title LIKE '%$keywords%'
			OR subtitle LIKE '%$keywords%'
			OR news_entry LIKE '%$keywords%'
		";
		$r = mysqli_query($dbc, $q);
			 // If results were found, output them
			 $retrieved = mysqli_num_rows($r);
			  if (@mysqli_num_rows($r) > 0) {
				echo "<h3>" . $retrieved . ' result(s) found, as follows:</h3>';	
				while ($row = mysqli_fetch_array($r)) {
					echo	"<div class='news_borders_top_bottom'>" .
							'<h1>' . $row['title'] = str_replace($_POST['keywords'], "<div class='highlight'>{$_POST['keywords']}</div>", $row['title']); . '</h1>' .
							'<h2>' . $row['subtitle'] = str_replace($_POST['keywords'], "<div class='highlight'>{$_POST['keywords']}</div>", $row['subtitle']); . '</h2>' .
							'<p>' . $row['news_entry'] = str_replace($_POST['keywords'], "<div class='highlight'>{$_POST['keywords']}</div>", $row['news_entry']); . '</p>' .
							'<div class="created_on">Created on: ' . $row['created'] . '</div></div>';
						     }
			     mysqli_close($dbc);
			     echo "<p><a href='search_archive.php'>Search again</a></p>";		
			?>
			    </div>
			  </div>
			  <?php 
				include('includes/footer.php');
				exit();	
			  } 
			  else { // no matches
			    echo "No news entries were found which matched your search criteria.";
			    }
			  }	  
  else { // no search term entered
	echo "Please enter a search term.";
	}
} else {  // search button not yet clicked so show form
	?>
	<h1>Search News Archive</h1>
		<form  method="post" action="search_archive.php" id="searchform"> 
			<p><input type="text" id="keywords" name="keywords"> </p>
			<p><input type="submit" name="submit" value="Search!"> </p>
		</form>
	</div>
	</div>
	<?php 
}
?>

Link to comment
Share on other sites

Well, what debugging have you done and what were the results? This is programming 101. If you are not getting the results you expect, then you need to add some debugging code to the page to "see" what the data is so you can check if the data is what you expect it to be.

 

Is the page named "search_archive.php" as you have specified in the action parameter of the form?

 

Did you put a print_r($_POST) at the top of the page to verify what POST data is sent?

 

Have you "viewed source" on the page to verify what HTML code, if any, is actually there?

 

 

FYI: You aren't creating valid HTML pages. That is very poor practice. It is not hard to build code that will output a complete, valid HTML page for any of the success/error conditions.

Link to comment
Share on other sites

Pikachu2000, when I put...

error_reporting(E_ALL);
ini_set("display_errors", 1);

... inside the first php tag at the top and ran the page, I still got a blank page. View source also showed a blank page.

 

Mjdamato, yes, the page is called search_archive.php. When I included a print_r($_POST) statement as per your suggestion, still a blank.

About the (in)valid HTML pages, sorry, I didn't include the full page which is below. (header.php contains doctype declaration, menubar, css and js includes, etc. So, is my page still a no-no from the point of view of validity?... I'm an enthusiast, not a pro...)

<?php
$page_title = 'Search News Archive';
include('includes/header.php');
include('includes/left_sidebar.php');
?>
</div>
  </div>
<div id="c2">
<div class="content">
<!-- main column content start -->
<?php 
if($_SERVER['REQUEST_METHOD'] == 'POST') { // form submitted
  if(!empty($_POST['keywords'])) { // search term has been entered
		$keywords = trim($_POST['keywords']);
		$search_exploded = explode(" ", $keywords);
		include('includes/mysqli_connect.php'); // connect to db
		// execute query
		$q = "SELECT title, subtitle, news_entry
		FROM news
		WHERE title LIKE '%$keywords%'
			OR subtitle LIKE '%$keywords%'
			OR news_entry LIKE '%$keywords%'
		";
		$r = mysqli_query($dbc, $q);
			 // If results were found, output them
			 $retrieved = mysqli_num_rows($r);
			  if (@mysqli_num_rows($r) > 0) {
				echo "<h3>" . $retrieved . ' result(s) found, as follows:</h3>';	
				while ($row = mysqli_fetch_array($r)) {
					echo	"<div class='news_borders_top_bottom'>" .
							'<h1>' . $row['title'] = str_replace($_POST['keywords'], "<div class='highlight'>{$_POST['keywords']}</div>", $row['title']); . '</h1>' .
							'<h2>' . $row['subtitle'] = str_replace($_POST['keywords'], "<div class='highlight'>{$_POST['keywords']}</div>", $row['subtitle']); . '</h2>' .
							'<p>' . $row['news_entry'] = str_replace($_POST['keywords'], "<div class='highlight'>{$_POST['keywords']}</div>", $row['news_entry']); . '</p>' .
							'<div class="created_on">Created on: ' . $row['created'] . '</div></div>';
						     }
			     mysqli_close($dbc);
			     echo "<p><a href='search_archive.php'>Search again</a></p>";		
			?>
			    </div>
			  </div>
			  <?php 
				include('includes/footer.php');
				exit();	
			  } 
			  else { // no matches
			    echo "No news entries were found which matched your search criteria.";
			    }
			  }	  
  else { // no search term entered
	echo "Please enter a search term.";
	}
} else {  // search button not yet clicked
	?>
	<h1>Search News Archive</h1>
		<form  method="post" action="search_archive.php" id="searchform"> 
			<p><input type="text" id="keywords" name="keywords"> </p>
			<p><input type="submit" name="submit" value="Search!"> </p>
		</form>
	</div>
	</div>
	<?php 
}
include('includes/footer.php');
?>

 

Link to comment
Share on other sites

I didn't include the full page which is below. (header.php contains doctype declaration, menubar, css and js includes, etc. So, is my page still a no-no from the point of view of validity?... I'm an enthusiast, not a pro...)

 

Hard to say. It definitely isn't the most efficient structure. You will find a big benefit from separating your logic (core PHP code) from the presentation (HTML & CSS). In the case of what you are trying to achieve, I would make a determination if tehre were results to display or not, then include() the display page. If there were errors (i.e. "No news entries were found...") I would assign those errors to a variable. Then if there were errors or if the form was not submitted I would include() the form page which would have a small section to display the error if there was one.

 

As to your specific problem. I would strip the entire page down to nothing more than a simple form, submit it and check the $_POST data. There could be something in the included header/footer pages that is causing a problem.

 

Another tip. When developing do one thing at a time, test/check the results, then move on to the next thing. When you try and develop many different steps at once and run into a problem you don't know what is causing the problem

Link to comment
Share on other sites

Mjdamato, that's been very, very helpful, thanks. I'll look again at - and rewrite - the code, keeping your advice in mind.

 

In the meantime, I've discovered that the problem lies in the lines below, where I'm trying to highlight the search criteria in the results returned by the search:

echo	"<div class='news_borders_top_bottom'>" .
'<h1>' . $row['title'] = str_replace($_POST['keywords'], "<div class='highlight'>$_POST['keywords']</div>", $row['title']); . '</h1>' .
'<h2>' . $row['subtitle'] = str_replace($_POST['keywords'], "<div class='highlight'>$_POST['keywords']</div>", $row['subtitle']); . '</h2>' .
'<p>' . $row['news_entry'] = str_replace($_POST['keywords'], "<div class='highlight'>$_POST['keywords']</div>", $row['news_entry']); . '</p>' .
'<div class="created_on">Created on: ' . $row['created'] . '</div></div>';

 

When I simply echo the records containing the search term (without any highlighting), the search functionality works fine. Now all I need to do is figure out the highlighting...

Link to comment
Share on other sites

Thanks, everybody, for your help with this. I found a solution, rewriting some code as follows:

 

while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
   $ttl = preg_replace('/(?![^<>]*>)'.preg_quote($keywords,"/").'/i', '<span class="highlight">$0</span>', $row['title']);
   $subt = preg_replace('/(?![^<>]*>)'.preg_quote($keywords,"/").'/i', '<span class="highlight">$0</span>', $row['subtitle']);
   $nws = preg_replace('/(?![^<>]*>)'.preg_quote($keywords,"/").'/i', '<span class="highlight">$0</span>', $row['news_entry']);
   echo "<div class='news_borders_top_bottom'>" .
      '<h1>' . $ttl . '</h1>' .
      '<h2>' . $subt . '</h2>' .
      '<p>' . $nws . '</p>' .
      '<div class="created_on">Created on: ' . $row['created'] . '</div></div>';
}

 

Now the search function, as well as the highlighting, works fine.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.