Jump to content

Recommended Posts

Below is the standard approach I take to writing my Prepared Statements...

 

// **********************************
// Create 'Total Visitors' Dataset.	*
// **********************************
$q9 = "SELECT COUNT(DISTINCT visitor_id) AS total_vistors
		FROM visitor_log
		WHERE member_viewed=?";

// Prepare statement.
$stmt9 = mysqli_prepare($dbc, $q9);

// Bind variable to query.
mysqli_stmt_bind_param($stmt9, 'i', $sessMemberID);

// Execute query.
mysqli_stmt_execute($stmt9);

// Store results.
mysqli_stmt_store_result($stmt9);

// Check # of Records Returned.
if (mysqli_stmt_num_rows($stmt9)==1){
	// Query Succeeeded.

	// Bind result-set to variables.
	mysqli_stmt_bind_result($stmt9, $visitorCount);

}else{
	// Query Failed.
	// Do Nothing...

}//End of CREATE TOTAL VISITORS DATASET

 

 

In the // Check # of Records Returned. section, normally on a SELECT query I would be check if if (mysqli_stmt_num_rows($stmt9)>0), and if records are returned (THEN) I would assign the results to variables (ELSE) I would re-direct to an Error-Page.

 

But since my query uses a Function, I'm not sure how to tweak my code?  :shrug:

 

- Do I just assume that it runs successfully?

 

- Is the way I modified things okay?  (In this particular case, I don't want to display an error if the query fails, because that would mean my entire "profile.php" page gets re-routed to an error page for something that is really non-fatal).

 

- I guess on the ELSE, I should probably do $visitorCount=''; or $visitorCount=0;

 

What do you think?!

 

 

Debbie

 

 

Link to comment
https://forums.phpfreaks.com/topic/264905-error-handling-if-count-fails/
Share on other sites

Why not make the function return true/false, and then redirect to an error screen based on that?

 

if(!visitorCount()){
    // redirect to error
}

 

I don't follow why you would want to return TRUE?

 

A "visitorCount" of TRUE is meaningless?!  (I can see a "visitorCount" of FALSE, though.)

 

My bigger question is, "Do I really care or need to handle if my Function and or Query fail??

 

(I'm not exactly TD AmeriTrade here!!)  *LOL*

 

The only reason my Function would fail would be a database or server hiccup, and as long as much code handles that "gracefully", I am hoping that is good enough for a value that is mainly "decorative"...

 

What does everyone else think?!

 

 

Debbie

 

True would mean the query (and therefore the function itself) executed correctly and you were able to get the visitor count.  I'm not sure why that would be odd/confusing.  Boolean flags are quite common.

 

IMO, you should, at the very least, log errors of this nature. 

True would mean the query (and therefore the function itself) executed correctly and you were able to get the visitor count.  I'm not sure why that would be odd/confusing.  Boolean flags are quite common.

 

IMO, you should, at the very least, log errors of this nature.

 

Are you saying the Function would return TRUE + VisitorCount on success?

 

 

Debbie

 

True would mean the query (and therefore the function itself) executed correctly and you were able to get the visitor count.  I'm not sure why that would be odd/confusing.  Boolean flags are quite common.

 

IMO, you should, at the very least, log errors of this nature.

 

Are you saying the Function would return TRUE + VisitorCount on success?

 

 

Debbie

 

 

Does your function currently return anything?  I don't see you doing anything with $visitorCount.

 

That said, remember our last conversation about how boolean true can be represented.  Any value that can be represented as a non-zero integer will be true.

Does your function currently return anything?  I don't see you doing anything with $visitorCount.

 

Here is my converted Query to Function code...

 

//****************************************************************************
function getProfile_TotalVisitors($dbc, $sessMemberID){
	/**
	 * Returns Total Unique Visitors to a Member's Profile.
	 *
	 * Take logged in Member's ID and determine how many people have visited
	 * the Member's Profile, including Other Members and Anonymous Visitors.
	 *
	 * Written On: 2012-06-27

	 * @param	Object		$dbc
	 * @param Integer		$sessMemberID
	 * @return Integer
	 */

	$q1 = "SELECT COUNT(DISTINCT visitor_id) AS total_visitors
					FROM visitor_log
					WHERE member_viewed=?";

	// Prepare statement.
	$stmt1 = mysqli_prepare($dbc, $q1);

	// Bind variable to query.
	mysqli_stmt_bind_param($stmt1, 'i', $sessMemberID);

	// Execute query.
	mysqli_stmt_execute($stmt1);

	// Store results.
	mysqli_stmt_store_result($stmt1);

	// Check # of Records Returned.
	if (mysqli_stmt_num_rows($stmt1)==1){
		// Query Succeeeded.

		// Bind result-set to variables.
		mysqli_stmt_bind_result($stmt1, $totalVisitors);

		// Fetch record.
		mysqli_stmt_fetch($stmt1);

	}else{
		// Query Failed.
		$totalVisitors = '';

	}

	return number_format($totalVisitors, ',');
}
//****************************************************************************

 

 

 

That said, remember our last conversation about how boolean true can be represented.  Any value that can be represented as a non-zero integer will be true.

 

Yes, I do recall that.

 

 

Debbie

 

 

Okay, well your returned $totalVisitors will automatically give you true, assuming that number will never be 0.

 

Yes, I guess.

 

But here is the kicker...

 

(Remember I am a NEWBIE here...)

 

The way I created my website's error-handling is like this...

 

		// Check # of Records Returned.
		if (mysqli_stmt_num_rows($stmt1)==1){
			// Details Found.
			// Do something...

		}else{
			// Details Not Found.
			$_SESSION['resultsCode'] = 'DETAILS_NOT_FOUND_2133';

			// Set Error Source.
			$_SESSION['errorPage'] = $_SERVER['SCRIPT_NAME'];

			// Redirect to Display Outcome.
			header("Location: " . BASE_URL . "/account/results.php");

			// End script.
			exit();

 

So whenever there is an error, I re-direct to my "results.php" script which logs the error by inserting a record in an Error Table and then I display the Erro with possible options to take action like this...

 

// Details Not Found.
case 'DETAILS_NOT_FOUND_2133':
	echo '<h1>Details Not Found</h1>';
	echo '<p>Your member details could not be displayed due to a System Error.</p>';
	echo '<p>Please try again. (2133)</p>';
	echo '<a class="button" href="' . BASE_URL . '/account/my_account.php">Return to My Account</a>';
	break;

 

I think this system work very well, except for two problems in this case...

 

1.) My code is not set up to JUST log an error without also displaying an Error-Page

 

2.) If an insignificant things like "getVisitorCount()" fails, I do NOT want to redirect to an Error-Page - especially since it was a technical snafu and nothing the User can fix.

 

I mean I do have a fair amount of Errors that I handle like this...

 

// Member Not Found.
case 'EDIT_COMMENT_MEMBER_NOT_FOUND_2310':
	echo '<h1>System Error</h1>';
	echo '<p>A Fatal Error has occurred.  Please contact the System Administrator. (2310)</p>';
	break;

 

...but that just seems like overkill here?

 

Maybe that is what I should do?!  :shrug:

 

 

I do know that I am sure there is a MUCH more sophisticated way of logging errors than what I have, but we all have to start from somewhere, right?!

 

 

Debbie

 

 

You need to decouple logging an error from displaying an error.  While both fall under the general heading of error handling, they're opposite sides of the process and (as you're now seeing) not necessarily dependent on one another.

 

You should be able to stick the code that logs the error in a function.  That way, you can log errors without a redirect.  results.php should only serve as an error screen when needed.

You need to decouple logging an error from displaying an error.  While both fall under the general heading of error handling, they're opposite sides of the process and (as you're now seeing) not necessarily dependent on one another.

 

You should be able to stick the code that logs the error in a function.  That way, you can log errors without a redirect.  results.php should only serve as an error screen when needed.

 

I'm sure you are right on all of this, but I'd say this is a Version 3.0 project.  (I'm finishing up v2.0 now)

 

The risk of me doing something seemingly simple and breaking all of my code would be catastrophic?!

 

 

Debbie

 

 

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.