Jump to content

Trying to understand the logic of the if and else statement


piano0011

Recommended Posts

Hey guys!

Thanks for your patience here... I know that I still have a lot to learn but I am trying to understand some of the basic of the if and else statement.... I have two separate codes and the first one is part of a longer code but not how to find out which part of the {} I should put the else statement, I guess I shouldn't be guessing at all.... thanks!

 

Example code 1:

if(!isset($_SESSION['u_uid'])) {
  header("Location: index.php?level1=notlogin");
  exit();
} else {
  include_once 'includes/dbh.php';

 



                           //Created a template
                            $sql = "SELECT * FROM memberships WHERE user_uid = ?;";
                            //Create a prepared statement

                            $stmt = mysqli_stmt_init($conn);
                            //Prepare the prepared statement
                            if (!mysqli_stmt_prepare($stmt, $sql)) {
                                echo 'SQL statement failed';
                            } else {
                                 //Bind parameters to the placeholder
                                 mysqli_stmt_bind_param($stmt, "s", $_SESSION['u_uid']);
                                 //Run parameters inside database
                                 mysqli_stmt_execute($stmt);
                                 
                                    $result = mysqli_stmt_get_result($stmt);

                                 while ($row = mysqli_fetch_assoc($result))  {
                                 
                                
                                     


                                     if ($row['subscriptionplan'] === 'Level 1' && $row['activate'] ==0 && $row['level1promo_activate'] == 0) {

                                         header("Location: index.php?level1=notactivated");
                                         exit();

                                      } else {
                                          if ($row['subscriptionplan'] === 'Level 1' && $row['activate'] == 1 && $row['emailreminder'] == 0 && date("Y-m-d H:i:s") > $row['paidbydate'] && $row['paid'] == 0 && $row['overdue'] == 0) {

Example code 2:

<?php

 
   
	include_once 'dbh.php';
    $uid = $_POST['user_uid'];
    $temporary_password = $_POST['temporary_password'];
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    
    $hashedpassword = password_hash($temporary_password, PASSWORD_DEFAULT);
    
    $password_verify =  password_verify($temporary_password, $hashedpassword);




    

    
        $hashednewpassword = password_hash($confirm_password, PASSWORD_DEFAULT);
        
        $sql = "SELECT * FROM users where  user_uid = ?;";

    $stmt = mysqli_stmt_init($conn);
    
    if (!mysqli_stmt_prepare($stmt, $sql)) {
        echo "SQL error";
    } else {
        mysqli_stmt_bind_param($stmt, "s", $uid);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $resultCheck = mysqli_num_rows($result);

        if ($resultCheck > 0) {

         while ($row = mysqli_fetch_assoc($result)) {
            $current_password = $row['user_password'];

            if ($current_password != $password_verify) {
                header("Location: index.php?changepassword2=notmatched");
                exit();
            } else {
                 $sql = "UPDATE users
                    SET user_password = ?
                    WHERE user_uid = ?
                   ";

             $stmt = mysqli_stmt_init($conn);

             if (!mysqli_stmt_prepare($stmt, $sql)) {
                 echo "SQL error";

             } else {

               mysqli_stmt_bind_param($stmt, "ss", $hashednewpassword, $uid);
               mysqli_stmt_execute($stmt);

               
             } 

               header("Location: ../index.php?changepassword2=success");
               exit();
             } 


        }
      }         else {
                header("Location: ../index.php?changepassword2=error");
                exit();

    }
            }
        


                                             

 

Link to comment
Share on other sites

i'm not sure if (programming pun intended) or what the question is? if you are asking what a php if/else statement does, please see the control structure section of the php.net documentation - http://php.net/manual/en/language.control-structures.php if you are asking when you should use an if(){} or if(){}else{} statement or what code you should put in each part of the if/else statement, that depends on what you have defined you want the code to do.

conditional statements control which code gets executed, based on the Boolean result of the expression being evaluated. the if(){...} block of code gets executed if the expression evaluates to a true value. the else {...} block of code gets executed if the expression evaluates to a false value.

if you want to redirect the user to a different page if they are not logged in, you would use an if(){...} statement. the expression being evaluated would be a value that indicates the not logged in state. the code that gets executed would perform the redirect.

btw - in the 1st piece of code, the first else {} is not need and should be removed, because the if(){} code exits and halts program execution when the expression is true. just put the remainder of the code after the closing } of the if(){} statement.

 

 

Link to comment
Share on other sites

I should have made the question a bit clearer but if I place the else statement here, then it won't work... I get an unexpected else... I guess my main question is why do we get an unexpected else and how to fix that problem? If I placed the else straight after the header success, then it will give me an unexpected else error....

 

<?php

 
   
	include_once 'dbh.php';
    $uid = $_POST['user_uid'];
    $temporary_password = $_POST['temporary_password'];
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    
    $hashedpassword = password_hash($temporary_password, PASSWORD_DEFAULT);
    
    $password_verify =  password_verify($temporary_password, $hashedpassword);




    

    
        $hashednewpassword = password_hash($confirm_password, PASSWORD_DEFAULT);
        
        $sql = "SELECT * FROM users where  user_uid = ?;";

    $stmt = mysqli_stmt_init($conn);
    
    if (!mysqli_stmt_prepare($stmt, $sql)) {
        echo "SQL error";
    } else {
        mysqli_stmt_bind_param($stmt, "s", $uid);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $resultCheck = mysqli_num_rows($result);

        if ($resultCheck > 0) {

         while ($row = mysqli_fetch_assoc($result)) {
            $current_password = $row['user_password'];

            if ($current_password != $password_verify) {
                header("Location: index.php?changepassword2=notmatched");
                exit();
            } else {
                 $sql = "UPDATE users
                    SET user_password = ?
                    WHERE user_uid = ?
                   ";

             $stmt = mysqli_stmt_init($conn);

             if (!mysqli_stmt_prepare($stmt, $sql)) {
                 echo "SQL error";

             } else {

               mysqli_stmt_bind_param($stmt, "ss", $hashednewpassword, $uid);
               mysqli_stmt_execute($stmt);

               
             } 

               header("Location: ../index.php?changepassword2=success");
               exit();
             } else {
                header("Location: ../index.php?changepassword2=error");
                exit();


        }
      }         

    }
            }
        

 

Link to comment
Share on other sites

as to the error, an else {} statement requires a corresponding opening if(){} statement. i can only guess that you are trying to add an else {} because you have some code (the success redirect) in the wrong place and you are not actually reading the code and seeing where the opening { and closing } are at now.

before going any further, you need to add missing features and simplify the existing code. at a minimum do the following -

1) detect that a post method form has been submitted before referencing any of the $_POST data.

2) validate all input data before using it. use an array to hold validation error messages. this will let you validate all the data at once and then display all the errors when you re-display the form.

3) the form processing code and the form need to be on the same page. this will eliminate all the header() redirects and it will let you re-populate the form with the submitted data when there is a validation error, so that the visitor doesn't need to keep reentering the same data over an over.

4) don't copy variables to other variables without a good reason. one good reason when processing user submitted values would be to trim() the data, so that you can detect all white-space characters. you can do this with a single line of code that operates on the data as a set.

5) password_hash() is used on the password you are going to insert/update in the database table. password_verify() is used to compare the stored hashed password with a submitted password. all other uses of these that you have in your code now are not doing anything useful and in the case of trying to compare the stored hashed password with the submitted password, you need to use password_verify() after you have fetched the stored hashed password.

6) don't use mysqli_stmt_init() and mysqli_stmt_prepare(). just use mysqli_prepare(). it does the same thing with one statement.

7) use exceptions to handle database statement (connection, query, prepare, execute) errors. this will simplify the code (you can remove the conditional logic you have now) and give you error handling for all the statements (the execute call can fail too, but you don't have any error handling for it.) to enable exceptions for the mysqli extension, add the following line before the point where you are making the database connection -

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

8 ) don't use mysqli_stmt_get_result() it results in non-portable code. this statement may work on your development system and current web host, but it may not on a different web host. if you move to a different host, you may have to rewrite the code. it is better to avoid using statements that may not exist. in fact, you need to switch to use the php PDO extension (Barand posted an example in one of your threads.) the PDO extension doesn't have any statements that may not exist and it is overall simpler and more consistent to use than the mysqli extension. 

9) the query in the code will at most match one row. don't use a loop to fetch the data. this is just cluttering up your code with unnecessary logic and syntax. Keep It Simple - KISS.

Link to comment
Share on other sites

Wow... so much to read but will go through it more thoroughly tomorrow...you mentioned not to use mysqli_stmt_prepare, just use mysqli_prepare but is this for procedure because pdo looks hard. I tried it once but just couldn't understand it much. 

I thought that most php tutorials are using mysqli_stmt_prepare? I just leant this prepared statement not long ago 

 

So in future, i should keep all php code at the top but because i have following a tute where he has a link to a header... is this not recommended?

 

You also mentioned that for the first code, the first else is not needed. I have been doing this in all my other pages.. could this be a reason for a redirect too many times error?

Link to comment
Share on other sites

the following is a single page password reset example, showing the recommendations listed above -

<?php
// define some 'helper' functions - these would typically be defined in an external .php file and 'required' when needed
// apply html htmlentities to a value
function _ent($val)
{
	return htmlentities($val); // this uses the current/default character encoding setting
}

// return an element from an array - used to reference array elements that might not be set
function _element($arr,$index)
{
	return isset($arr[$index]) ? $arr[$index] : '';
}

// recursive function to trim data.
function _trim($val)
{
	if(is_array($val))
	{
		return array_map('_trim',$val);
	} else {
		return trim($val);
	}
}

// define an array of the expected/required form fields
$fields = [];
$fields['user_uid'] = ['label'=>'Username']; // i suspect the user_uid is actually the username
$fields['temporary_password'] = ['label'=>'Existing Password']; // suspect temporary pwd is a generated pwd, in any case it is the existing password 
$fields['password'] = ['label'=>'New Password'];
$fields['confirm_password'] = ['label'=>'Confirm New Password'];


$errors = []; // define an array to hold validation errors
$post = []; // define an array to hold a working copy of the submitted form data

// form processing code
if($_SERVER['REQUEST_METHOD'] == 'POST') // this is a general purpose way of detecting if a post method form has been submitted. 
{
	// get a trimmed copy of the submitted form data
	$post = array_map('_trim',$_POST);
	
	// validate the submitted data
	
	// check that the required fields are not empty
	foreach($fields as $field=>$arr)
	{
		if($post[$field] == '')
		{
			$errors[$field] = "{$arr['label']} is empty.";
		}
	}

	// check if the password/confirm_password match
	if(empty($errors['password']) && empty($errors['confirm_password']) && $post['password'] != $post['confirm_password'])
	{
		$errors['password'] = "The {$fields['password']['label']} and {$fields['confirm_password']['label']} are not the same.";
	}
		
	// if the new password must meet any length or 'strength' requirements, validate those here...
	
	// at this point, if there are no errors, use the submitted form data
	if(empty($errors))
	{
		// use the data in $post here...
		require 'dbh.php';

		// get the current password for the user
		$sql = "SELECT user_password FROM users where user_uid = ?";
		$stmt = $pdo->prepare($sql);
		$stmt->execute([$post['user_uid']]);
		if(!$row = $stmt->fetch())
		{
			// the user doesn't exist
			$errors['user'] = "The username/password is incorrect."; // a generic message to help prevent finding valid usernames
		} else {
			// the user does exist, check the existing password
			if(!password_verify($post['temporary_password'],$row['user_password']))
			{
				// password doesn't match
				$errors['user'] = "The username/password is incorrect."; // a generic message to help prevent finding valid usernames
			} else {
				// password does match, update the password
				$sql = "UPDATE users
					SET user_password = ?
					WHERE user_uid = ?
				";
				$stmt = $pdo->prepare($sql);
				$stmt->execute([password_hash($post['password'], PASSWORD_DEFAULT),$post['user_uid']]);
			}
		}
	}
	// at this point, if there are no errors, the form processing code was successful
	if(empty($errors))
	{
		// do whatever you want when the password reset was successful
	}
}

// output the html document starting here...
?>
<!DOCTYPE html>
  <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>Reset password</title>
    </head>
  <body>
   <?php
   // display any errors
   if(!empty($errors))
   {
	   echo implode('<br>',$errors);
   }
   ?>
   <form method="POST">
     <input type="text" name="user_uid" placeholder="Username" value='<?php echo _ent(_element($post,'user_uid')); ?>'>
     <br>
     <input type="text" name="temporary_password" placeholder="Existing Password" value='<?php echo _ent(_element($post,'temporary_password')); ?>'>
     <br>
     <input type="text" name="password" placeholder="New Password" value='<?php echo _ent(_element($post,'password')); ?>' >
     <br>
     <input type="text" name="confirm_password" placeholder="Confirm New Password" value='<?php echo _ent(_element($post,'confirm_password')); ?>'>
     <br><br>
     <button type="submit" name="submit" class="button">Reset Password</button>
   </form>
 </body>
 </html>

you don't have to understand OOP notation in order to use it. calling an OOP class method is really no different than calling a procedural function.

compare the PDO statements on ~ lines 70-72 and 88-89 with the massive number of mysqli statements you have in your code, and decide which you would rather be using. you will also note that the sql syntax for ? prepared query place-holders is the same between mysqli and PDO, so you don't have to change any of the sql syntax.

Link to comment
Share on other sites

2 minutes ago, piano0011 said:

I forgot to add that i thought you need an else for every if statement because you mentioned that the first else should be omitted from the 1st code

here is where reading the introductory sections in the php.net documentation will help (i linked to it above.) you will learn what actually exists and how to use it.

Link to comment
Share on other sites

25 minutes ago, piano0011 said:

You also mentioned that for the first code, the first else is not needed. I have been doing this in all my other pages.. could this be a reason for a redirect too many times error?

the redirect error is because you are redirecting to the same page and the logic you have on the page causes more redirects. the way to fix this is to correct the logic, firstly by not redirecting all over the place.

i posted some example code about 5 replies above this (the new forum software doesn't number replies, so i cannot refer you to a post number), using this structure for form processing and the form will eliminate the need for all but one redirect and that redirect will be inside the post method form processing code, which won't be executed upon the redirect since there won't be any post data after the redirect.

Link to comment
Share on other sites

You also mentioned that the form and php process should occur on the same page? Can i have the form action set to another page? Is it a common practice? 

Also thanks for pointing that out because i thought that you can redirect to the same page

 

Link to comment
Share on other sites

The better practice is to have everything in one page (excluding headers and footers that you could separate and include). PHP at the top of the page, HTML at the bottom. Psuedo Code...
 

<?php
if server request method == post{
//Process form
}
// Do not exit to re display same page. No redirect needed.
?>

HTML HERE

Completely remove the action to submit to same page.

 

 

Link to comment
Share on other sites

you can put the form and the form on different pages, but by putting them on separate pages, you will have the disadvantages you are experiencing in this thread, of having to redirect back to the form upon an error and not being able to repopulate the form fields. this also takes more code.

you can redirect to the same page, but your program logic must prevent further redirects? are you at the point where you can figure out how to prevent the redirect loop?

Link to comment
Share on other sites

This is interesting and i am still thinking about this but i think that my main page is working now after putting my html at the bottom of the code...i also have made sure that i am redirecting to a different page... but since this is my first website, i just like your opinion on what do you think about having the <?php include_once 'header.php?  According to mmtuts, he said that this will make each page uniform?

Link to comment
Share on other sites

37 minutes ago, piano0011 said:

This is interesting and i am still thinking about this but i think that my main page is working now after putting my html at the bottom of the code...i also have made sure that i am redirecting to a different page... but since this is my first website, i just like your opinion on what do you think about having the <?php include_once 'header.php?  According to mmtuts, he said that this will make each page uniform?

Including headers and footers is exactly what I mentioned a couple posts up. It is perfectly acceptable and a good practice if you have the same header and/or footer content across multiple pages.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.