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.

<?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();
?>
Member Avatar for diafol
if($result->num_rows > 0){
  ...(do this)...
}else{
  ...(do this instead)...
}

//EDIT
Hmm, sim post C.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.