0

What I would like to do is return a basic text message if no results are returned from my database.

Using the following code can someone tell me how I can accomplish this. Please excuse the code if its sloppy, Im a beginner at php.

<?php
// create short variable names
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo 'You have not entered search details.';
exit;
}
if (!get_magic_quotes_gpc()){
$searchtype = addslashes($searchtype);
$searchterm = addslashes($searchterm);
}
@ $db = new mysqli('localhost', 'username', 'password', 'database');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "select * from books where ".$searchtype." like '%".$searchterm."%'";
$result = $db->query($query);
$num_results = $result->num_rows;
for ($i=0; $i <$num_results; $i++) {
$row = $result->fetch_assoc();
echo "<div class='mess'><strong>";
echo htmlspecialchars(stripslashes($row['title']));
echo "</br></strong><br /><strong>Found:</strong> </br></div>";
echo stripslashes($row['author']);
}
$db->close();
?>

Thank you guys.

Edited by valonesal: n/a

3
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by valonesal
0
<?php
// create short variable names
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
	echo 'You have not entered search details.';
	exit;
}
if (!get_magic_quotes_gpc()){
	$searchtype = addslashes($searchtype);
	$searchterm = addslashes($searchterm);
}
$db = new mysqli('localhost', 'username', 'password', 'database');
if (mysqli_connect_errno()) {
	echo 'Error: Could not connect to database. Please try again later.';
	exit;
}
$query = "select * from books where ".$searchtype." like '%".$searchterm."%'";
$result = $db->query($query);
$num_results = $result->num_rows;
if ($num_results) { // add this
	for ($i=0; $i <$num_results; $i++) {
		$row = $result->fetch_assoc();
		echo "<div class='mess'><strong>";
		echo htmlspecialchars(stripslashes($row['title']));
		echo "</br></strong><br /><strong>Found:</strong> </br></div>";
		echo stripslashes($row['author']);
	}
} else { // and this
	echo 'There were no results found.'; // stuff
} // here
$db->close();
?>
0
if($result->num_rows > 0){
  ...(do this)...
}else{
  ...(do this instead)...
}

//EDIT
Hmm, sim post C.

Edited by diafol: simultaneous post

0

Outstanding guys thank you for the help, I better understand how its done now.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.