Jump to content

Handling Variable the correct way


doubledee

Recommended Posts

I am uncertain of how to go about checking if my variables have values, and if I have to do this at every step in my code?!  :shrug:

 

For instance...

 

In my "Member" table, the fields "id" and "name" are required.  So when I run this query, presumably there are always values there, right?

 

// Build query.
$q = 'SELECT id, first_name
FROM member
WHERE email=? AND pass=?';

 

1.) Is that a fair assumption?

 

 

After the above code, I initialize these two variables...

 

// Initialize variables.
$memberID = $memberFirstName = '';

 

Next I have...

// Bind result-set to variables.
mysqli_stmt_bind_result($stmt, $memberID, $memberFirstName);

 

2.) Did I need to initialize those two variables if I am assigning them values a few lines down?

 

3.) Can I assume that "$memberID" and "$memberFirstName" will have values based on the comments above?

 

 

Then a few more lines after this, I have...

// Set Session variables.
$_SESSION['memberID'] = $memberID;
$_SESSION['memberFirstName'] = $memberFirstName;
$_SESSION['loggedIn'] = TRUE;

 

4.) Again, do I need to keep checking for values (e.g. using ISSET)??

 

I suppose *anything* is possible, but you could also make your code so full of error-checking code that it would come to a screeching halt?!

 

Please enlighten me!!

 

 

Debbie

 

 

Link to comment
Share on other sites

The mysql_num_rows() function returns the number of rows in a recordset.

<?php
$q = 'SELECT id, first_name	FROM member	WHERE email=? AND pass=?';
$r = mysql_query($q);
$numOFrows = mysql_num_rows($r);

if($numOFrows !=0 )
{
  echo $numOFrows;
}
else
{
	echo $numOFrows
}
?>

 

 

Link to comment
Share on other sites

I havn't ever actually used that function, but from what i read here

 

http://php.net/manual/en/mysqli-stmt.bind-result.php

 

it looks like you would be ok to not check them. I would recommend just taking out the checks and trying it out with values (or lack of values) that you know may screw it up.

i must have been tired when i wrote that. If you're worried about security i would check to make sure it is set. isset doesnt take up a ton of resources. Unless you have a server thats about to explode i really wouldnt worry about a couple extra checks.

Link to comment
Share on other sites

I havn't ever actually used that function, but from what i read here

 

http://php.net/manual/en/mysqli-stmt.bind-result.php

 

it looks like you would be ok to not check them. I would recommend just taking out the checks and trying it out with values (or lack of values) that you know may screw it up.

i must have been tired when i wrote that. If you're worried about security i would check to make sure it is set. isset doesnt take up a ton of resources. Unless you have a server thats about to explode i really wouldnt worry about a couple extra checks.

 

But the question is WHEN and WHY and HOW OFTEN do you have to check data that is being passed from page to page...

 

 

Debbie

 

 

Link to comment
Share on other sites

I am uncertain of how to go about checking if my variables have values, and if I have to do this at every step in my code?!  :shrug:

 

For instance...

 

In my "Member" table, the fields "id" and "name" are required.  So when I run this query, presumably there are always values there, right?

 

// Build query.
$q = 'SELECT id, first_name
FROM member
WHERE email=? AND pass=?';

 

1.) Is that a fair assumption?

 

If a row was actually returned, then yes, you can assume that id and first_name are present.  But, like voip was trying to point out, you need to ensure that you actually have a db row returned from your query before you can start working on the data you expect it to contain.

 

After the above code, I initialize these two variables...

 

// Initialize variables.
$memberID = $memberFirstName = '';

 

Next I have...

// Bind result-set to variables.
mysqli_stmt_bind_result($stmt, $memberID, $memberFirstName);

 

2.) Did I need to initialize those two variables if I am assigning them values a few lines down?

 

Technically, no.  I tend to declare variables before using them because it makes code more readable.  I hate seeing magic variables just pop up.  It's also required in other languages, which are tighter about type.

 

Finally, as a tip, you don't need to initialize a variable to an empty string unless you're going to add to the string later.  Something like:

 

$message = '';

foreach($something as $value)
{
   $message .= " something else ";
}

 

Doing it just because, especially if you're going to be putting non-string data in a variable (like your memberID), is pointless.  A simple:

 

$id, $name;

 

Will suffice, as it declares them before use.

 

3.) Can I assume that "$memberID" and "$memberFirstName" will have values based on the comments above?

 

Again, you need to check that your query returned results.

 

Then a few more lines after this, I have...

// Set Session variables.
$_SESSION['memberID'] = $memberID;
$_SESSION['memberFirstName'] = $memberFirstName;
$_SESSION['loggedIn'] = TRUE;

 

4.) Again, do I need to keep checking for values (e.g. using ISSET)??

 

Depends on the context.  If you're certain that the values you're storing in sessions exist, then no.  But that depends on what happened further up the script.  Generally, you'll have your success condition code inside a if-else anyway, so for the success condition to fire, everything would need to be correct up to that point.

 

If you're bringing these values into your script via sessions, then yes, you'll have to check them before using them.

 

I suppose *anything* is possible, but you could also make your code so full of error-checking code that it would come to a screeching halt?!

 

Isn't that the point of error checking?  To stop the entire operation and alert others when something bad happens?

 

Error checking is tedious.  It's also necessary.  An overabundance of caution is preferable to the alternative.

Link to comment
Share on other sites

If a row was actually returned, then yes, you can assume that id and first_name are present.  But, like voip was trying to point out, you need to ensure that you actually have a db row returned from your query before you can start working on the data you expect them to contain.

Thank you my guru

Link to comment
Share on other sites

If a row was actually returned, then yes, you can assume that id and first_name are present.

 

Okay.

 

 

Finally, as a tip, you don't need to initialize a variable to an empty string unless you're going to add to the string later.  A simple:

 

$id, $name;

 

Will suffice, as it declares them before use.

 

I did not know that.  Thanks!

 

 

Again, you need to check that your query returned results.

 

But if it returns a record, and my database has those fields as NOT NULL, then basically I can know those fields have values if there is a record there, right?

 

 

I suppose *anything* is possible, but you could also make your code so full of error-checking code that it would come to a screeching halt?!

 

Isn't that the point of error checking?  To stop the entire operation and alert others when something bad happens?

 

Error checking is tedious.  It's also necessary.  An overabundance of caution is preferable to the alternative.

 

Understood, but I also don't want to overdo it and check more than needed.

 

Using SESSION makes me nervous.

 

I am starting to see there are a lot of loopy things that can happen, and wish it was easier to pass data between scripts and maintain persistence more.

 

 

 

Debbie

 

P.S.  If voip03 would have been more clear then his/her comments would have made sense like yours...  ;)

 

 

Link to comment
Share on other sites

But if it returns a record, and my database has those fields as NOT NULL, then basically I can know those fields have values if there is a record there, right?

 

Correct.

 

I suppose *anything* is possible' date=' but you could also make your code so full of error-checking code that it would come to a screeching halt?![/quote']

 

Isn't that the point of error checking?  To stop the entire operation and alert others when something bad happens?

 

Error checking is tedious.  It's also necessary.  An overabundance of caution is preferable to the alternative.

 

Understood, but I also don't want to overdo it and check more than needed.

 

Unfortunately, there's no hard, fast rule which specifies what would be needed.  That's where thorough testing comes into play.

 

Using SESSION makes me nervous.

 

I am starting to see there are a lot of loopy things that can happen, and wish it was easier to pass data between scripts and maintain persistence more.

 

I think part of your problem is your design.  From what little code I've seen from you, it looks like you're doing things in just about the hardest way possible.  A login system and a comment system each has only a couple moving parts - is the person a registered user?  are they logged in?  can you tie their comment to a particular article?  The way you have things structured, and how you try to jump around from piece to piece, would leave many confused.

 

Design is one of the harder things to learn, and is usually only learned after hours of sweat and tears.

Link to comment
Share on other sites

I think part of your problem is your design.  From what little code I've seen from you, it looks like you're doing things in just about the hardest way possible.  A login system and a comment system each has only a couple moving parts - is the person a registered user?  are they logged in?  can you tie their comment to a particular article?  The way you have things structured, and how you try to jump around from piece to piece, would leave many confused.

 

Design is one of the harder things to learn, and is usually only learned after hours of sweat and tears.

 

Well, if you guys are willing to help me do a better job, I'm open to the help.  (Just respect that I want the look and feel and flow that I want.)

 

Since I cannot post my entire website here, let me try and summarize my process flow and why I don't think it is confusing.

 

 

STEP 1: User reads Article and wants to add a comment in the "Comments" section beneath the article.  (Par for the course on any online newspaper.) Visually...

 

Postage Meters can Save Your Money!!

Aug 31, 2011

By Debbie

 

Most small businesses don't realize how much money on postage they could save if they bought...

 

...the end.

 

--------------------------------------------------------------

COMMENTS: What do you think?

 

To add a comment you must...

 

*Log In button*  or * Create an Account button *

 

 

Comment #1: John Doe

I really liked Debbie's article.  It was very insightful.

 

 

Comment #2: Jane Doe

Yeah, I wish my husband would take Debbie's advice and start saving more money!

 

 

Comment #3: Lisa Jones

Hey Debbie, can I buy a Postage Meter fo home as well?!

---------------------------------------------------------------

 

 

STEP 2:  User clicks "Log In", is taken to "log_in.php" and logs in successfully.

 

--------------------------------------------------------------

LOG IN

 

Please log in to comment on the article:  "Postage Meters can Save You Money"

 

E-mail: ______________

 

Password: ____________

 

 

*LOG IN button*

---------------------------------------------------------------

 

 

STEP 3:  User is taken to "add_comment.php", types in a comment and submits it.

 

--------------------------------------------------------------

ADD A COMMENT

 

Article: "Postage Meters can Save You Money"

 

Commentor:  George Washington

 

Comment:  A horse is still cheaper...

 

 

*Submit button*

---------------------------------------------------------------

 

 

STEP 4:  User is taken back to original article in STEP 1.

 

Postage Meters can Save Your Money!!

Aug 31, 2011

By Debbie

 

Most small businesses don't realize how much money on postage they could save if they bought...

 

...the end.

 

--------------------------------------------------------------

COMMENTS: What do you think?

 

To add a comment you must...

 

*Log In button*  or * Create an Account button *

 

 

Comment #1: John Doe

I really liked Debbie's article.  It was very insightful.

 

 

Comment #2: Jane Doe

Yeah, I wish my husband would take Debbie's advice and start saving more money!

 

 

Comment #3: Lisa Jones

Hey Debbie, can I buy a Postage Meter fo home as well?!

 

 

Comment #4: George Washington

A horse is still cheaper...

---------------------------------------------------------------

 

 

That is visually how I want things to look and flow.  It is 3 steps and a pretty common approach.

 

I have it working, but am worried that maybe my code can be broken and so I could use some help making my code stronger and more secure.

 

Help is welcome!!!

 

Thanks,

 

 

Debbie

 

 

 

Link to comment
Share on other sites

Are you completely married to step 3?  Most sites have a text area directly below their content to allow users to add comments.  It's easier to implement that way (although certainly not impossible to do it your way).

 

Step 1:

 

The "Login or Register" portion should be based on a conditional.  If the person is not logged in, then it should show the login/register buttons.  If they are logged in, it should show an "Add Comment" (or something similar) button.  The easiest way to do this would be to use sessions.

 

Step 2:

 

When you go to the login screen, it will need to know what page you were on when you left to log in.  There are a couple ways to do this - sessions (again), or query string values.  I prefer query string values here.  The values should likely be content/page type (in this case, articles), and its particular id number.  So, something like site.com/login.php?page=articles&id=334

 

Step 3:

 

The same thing, really.  Use a header redirect with the same query string values appended to the end.

 

Step 4:

 

Easiest step.  Just redirect back to the article.

 

Not sure what else you'd need without seeing actual code, but that's how I'd approach it.

Link to comment
Share on other sites

Are you completely married to step 3?  Most sites have a text area directly below their content to allow users to add comments.  It's easier to implement that way (although certainly not impossible to do it your way).

 

Pretty much so.  (BTW, as I type my response to you, I am also in a separate window versus the "Quick Response" that you are referring to.)

 

 

Step 1:

 

The "Login or Register" portion should be based on a conditional.  If the person is not logged in, then it should show the login/register buttons.  If they are logged in, it should show an "Add Comment" (or something similar) button.  The easiest way to do this would be to use sessions.

 

Yes, that is what I am doing.  I have $_SESSION['loggedIn'] and if TRUE them my php displays "Add a Comment" and if not then "Log-In" or "Create an Account".

 

 

Step 2:

 

When you go to the login screen, it will need to know what page you were on when you left to log in.  There are a couple ways to do this - sessions (again), or query string values.  I prefer query string values here.  The values should likely be content/page type (in this case, articles), and its particular id number.  So, something like site.com/login.php?page=articles&id=334

 

For the longest time - until last night - I had a $_SESSION['returnToPage'] to do this because my flow went...

 

Article ----> Log In ----> Article ---> Add a Comment

 

But I figured that if I added a reference back to the article I could cut out returning to the Article and save an extra step!

 

"Please log-in to comment on the article: $_SESSION['pageTitle']

 

So now, I go directly from "Log In" to "Add a Comment".

 

 

Step 3:

 

The same thing, really.  Use a header redirect with the same query string values appended to the end.

 

Well, I actually reload "add_comment.php" and display a Success/Failure message like...

 

Comment Submitted

All submissions must be reviewed by an Administrator.

Once approved, your comment will appear below the article:

htmlspecialchars($pageTitle, ENT_QUOTES)

Thanks for sharing your thoughts!

 

---------

Comment Creation Failed

Your comment could not be added due to a system error.

 

 

Step 4:

 

Easiest step.  Just redirect back to the article.

 

So you think people want to return to the original article after commenting?  (Even though they won't see their comments for a while?)

 

 

Not sure what else you'd need without seeing actual code, but that's how I'd approach it.

 

Well, did you get a chance to review my code?

 

If so, how did it look?

 

Is there any way my use of Sessions could break things?

 

 

Debbie

 

 

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.