PHP error handling with exit

Hi guys I’m pulling my hair out with the following code. I’m trying to error check values entered into a search input field, specifically that it’s just alphanumerics that have been entered and that the input contains data.

In both instances, the error message is echoed but the exit(); obviously prevents the remainder of the page (eg footer include) from loading. If I ditch the exit(); then regardless of an error, information from the mysql database is displayed along with html tags used in the db…

I must say, that if no errors are triggered, the db outputs the information perfectly and without displaying the html tags as above.

It’s all very odd. Could you please have a look at my mess of code!!

<?php

	$searchtext = mysqli_real_escape_string($connection, $_POST['search']);

						if (!preg_match('/^[a-zA-Z0-9 ]*$/', $_POST['search'])){
									echo 'Only alphanumerics allowed.';
									exit();
								}
		
						if (empty($_POST['search'])){
									echo 'Please enter a search term.';
									exit();
						}
			
	$sql = "SELECT text.* FROM text WHERE output LIKE '%".$searchtext."%' OR altText LIKE '%".$searchtext."%'";
	$query=mysqli_query($connection, $sql);
	$result=mysqli_fetch_assoc($query);
	if(mysqli_num_rows($query)>0) {
		
		do {
			
			?>
			
			<ul>
			<li>
				<?php 
					
					echo $result['outputURL'];
					echo preg_replace("/(".$searchtext.")/i", "<span class='highlight'>$1</span>", $result['output']);	
				?>
			</li>
			</ul>
				<?php 
				
					} while ($result=mysqli_fetch_assoc($query));
			
						} else {
		
							echo 'Please refine your search term.';
							break; 
						}
			?>

Just to add, that I’ve tried placing the if statements in functions and do loops to leverage the use of return; and break; instead of exit(); but the problem persists.

I think what I would do instead of echo for each, is to assign the message to an array. eg.

$errors[] = "sorry, you're not tall enough for this ride"; 

then after the conditional checks, test to see if the $errors array is empty. If not, then echo the messages and exit;
If there are no errors, then use the values in the output.

Thank you for your input, but it’s the exit; that is the real problem, I guess. In using that, it’s breaking the rest of the page, so I need to find a way around that… I think.

If you output all the error messages and then the footer as @Mittineague suggested then the exit after that will not cause problems as the page will be complete

I believe I’ve tried this, as in the code below and although the footer is visible, the conditional checks do not work as expected. Again, the check for blank space dumps a large amount of db data (and displayed incorrectly) into the page and the alphanumeric check does not honour all symbols.

You’ll have to bear with me here, I’m a little out of my depth

The code:

<?php $searchtext = mysqli_real_escape_string($connection, $_POST['search']); $errors = array(); if (!preg_match('/^[a-zA-Z0-9 ]*$/', $_POST['search'])){ //echo $error = 'Only alphanumerics allowed.'; //exit(); $errors['value1'] = "alpha"; } if (empty($_POST['search'])){ //echo $error = 'Please enter a search term.'; //exit(); $errors['value2'] = "blank"; } $sql = "SELECT text.* FROM text WHERE output LIKE '%".$searchtext."%' OR altText LIKE '%".$searchtext."%'"; $query=mysqli_query($connection, $sql); $result=mysqli_fetch_assoc($query); if(mysqli_num_rows($query)>0) { do { ?>
							<ul>
							<li>
								<?php 
									
									echo $result['outputURL'];
									echo preg_replace("/(".$searchtext.")/i", "<span class='highlight'>$1</span>", $result['output']);	
								?>
							</li>
							</ul>
								<?php 
								
									} while ($result=mysqli_fetch_assoc($query));
							
										} else {
						
											echo $error = 'Please refine your search term.';
										}
							?>
							
							
							
																
									</div>	
										
										
										
										</section>
										
									</article>
							
								
							
							</div>

					</div>
				</div>
			</div>
		</div>
		
	<?php
		
		
		function form_errors($errors=array()) {
			$output = "";
			if (!empty($errors)) {
			  $output .= "<div class=\"error\">";
			  $output .= "Please fix the following errors:";
			  $output .= "<ul>";
			  foreach ($errors as $key => $error) {
			    $output .= "<li>{$error}</li>";
			  }
			  $output .= "</ul>";
			  $output .= "</div>";
			}
			return $output;
		}
	?>
	<?php echo form_errors($errors); ?>
	
	
		<?php mysqli_close($connection); ?>

	<?php include ($_SERVER['DOCUMENT_ROOT'].'/include/footer.php'); ?>
	
	<?php exit(); ?>

As a side note exiting the application is not error handling. Error handling would be recovering from the error allowing the application to continue execution. Also logging and/or providing feedback for the problem to correct the error. Simply exiting at the first sign of trouble is lazy.

Given that I’ve said a few times that I’m unsure of what I’m doing, saying that what I’m doing is lazy is a bit unfair.

Perhaps some guidance would’ve been a more constructive use of your time.

I believe oddz may be going by the topic title.
He is correct, exit is not handling an error, it is a way to stop the script from going any further.
And he is correct, it would be better to do something more when an error occurs.

Is using exit lazy? IMHO not for a beginner, as long as it doesn’t become an ingrained habit and is only an “until I know more” thing.

I give you credit for using mysqli There are members here that are so adept at giving reasons for using deprecated mysql it could make an addict justifying their habit look like an amateur.

Right now it seems you are having enough trouble getting the code flow correct, and that’s probably enough to deal with for now.

PHP lets programmers mix and mingle HTML with the PHP code, if they want or need to.
Going “in and out” of PHP gets messy fast, and you can find many heated debates about this.

But anyway, try something like this

<?php 
PHP code that needs to run before anything is output, 
headers, sessions, cookies, maybe includes / requires
?>
the "beginning" HTML stuff
<?php 
PHP code that puts together stuff that will be output 
if OK
somehow put it into HTML that will be output  
ELSE
put together whatever you want to show if everything is not OK
?>
the "ending" HTML stuff

that interface is no longer deprecated - the deprecation ended in December last year when it ceased to exist as a part of the latest PHP version.

2 Likes

I would disagree. Bad habits are tough to break.

Separation of concerns. Not a debate but a well known design principle. Otherwise you end up with kind of mess the opt posted. Imagine maintaining that throughout an entire medium-large scale application. I have and its no fun. Do things right the first time.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.