• PHP Help
  • Parse error: syntax error, unexpected 'else' (T_ELSE)

I have been trying to run a piece of PHP script for a number of user fields and I am continuing to get the parse error: unexpected 'else' (T_ELSE) on line 29 - the second else statement
I have checked that there is no semi colon after the if statement and all of the indenting appears to line up so I am not sure what is wrong. Could someone please assist. Thank you

<?php

if (issset($_POST['submit'])) {
	
require 'dbh.inc.php';

$firstname = $_POST['First name'];
$lastname = $_POST['Last name'];
$email = $_POST['Email'];
$number = $_POST['Phone number'];
$address = $_POST['Address'];
$pass = $_POST['Password'];

if (empty($firstname) or empty($lastname) or empty($email) or empty($number) or empty ($address) or empty($pass)) {
	
	header("Location: ../html-1column.html?error=emptyfields&firstname=".$firstname." &email=".$email."");
	exit();
}
else {
	
	$sql="SELECT Email FROM users WHERE Email=?";
	$stmt=mysqli_stmt_init($conn);
	if (!mysqli_stmt_prepare($stmt, $sql)) {
	header("Location: ../html-1column.html?error=sqlerror");
	exit();
	}
}

else {
	mysqli_stmt_bind_param($stmt, "s", $email);
	mysqli_stmt_execute($stmt);
	mysqli_stmt_store_result($stmt);
	$resultcheck = mysqli_stmt_num_rows($stmt);
	if ($resultcheck > 0){
	header("Location: ../html-1column.html?error=usertaken");
	exit();	

}
else {
	$sql="INSERT INTO users (First name, Last name, Email, Phone number, Address, Password) VALUES (?, ?, ?, ?, ?, ?)";
	$stmt=mysqli_stmt_init($conn);
	if (!mysqli_stmt_prepare($stmt, $sql)) {
	header("Location: ../html-1column.html?error=sqlerror");
	exit();
}

else {
	$hashedpwd = password_hash($pass, PASSWORD_DEFAULT);
	mysqli_stmt_bind_param($stmt, "ssssss", $firstname, $lastname, $email, $number, $address, $hashedpwd);
	mysqli_stmt_execute($stmt);
	header("Location: ../html-1column.html?signup=success");
	exit();
	
}

}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);

} #open 10
else {
	header("Location: ../html-1column.html");
		exit();
}
?>

    It doesn't make sense to have an ELSE followed by an ELSE.
    What you have is

    if (issset($_POST['submit'])) {
    	if (empty($firstname) or empty($lastname) or empty($email) or empty($number) or empty ($address) or empty($pass)) {
    	...
    	}
    	else {
    		...
    	}
    }
    else {
    	...
    
    }
    else {
    	...
    }
    else {
    	...
    }
    

    Every else needs to be paired with an if.

      Thanks so should I have else If... Do you have a suggestion of how I could better write this code? Thanks

      Added [code]...[/code] tags to the original post.

        You are probably not going to like this answer, because it will simplify what you are doing and eliminate almost all of that code -

        1. Your form processing code should be on the same page as the form. This will eliminate all but the last 'success' header() redirect. This will also let you validate all the inputs separately, setting up a unique and helpful error message for each input that is not valid. You would display any error messages when you re-display the form. You can also re-populate the form field values with the submitted data so that the visitor doesn't need to keep re-entering the same things over and over.
        2. Don't copy variables to other variables without a good reason. This is just a waste of time typing out lines of code for each form field. Instead, keep the set of form data as an array and just operate on elements of the array in the rest of the code.
        3. To correctly handle duplicate data values, define the column in your database table as a unique index, then just attempt to insert the data. If the value doesn't exist, the row will be inserted. If the value already exists, the query will produce a duplicate index error, that your code can detect by testing the error number from the query. This will eliminate all the logic associated with the SELECT query.
        4. You should not tell the visitor to your site that a database error occurred, except when the visitor can do something to correct the error, such as when inserting/updating duplicate data values. Your database error handling should use exceptions for errors and in most cases let php catch and handle the exception, where php will use its error related settings to control when happens with the actual error information (database statement errors will 'automatically' get displayed/logged the same as php errors.) For the case of inserting/updating user submitted data, you would catch any database exception and test if the error number is for a duplicate key error. If so, setup and display a message for the visitor telling them what was wrong with the data that they submitted. For all other error numbers, just re-throw the exception and let php handle it. This will eliminate all the database error handling logic, except for the execution of an insert/update query that needs to detect and handle duplicate submitted data. Using exceptions for errors will also give you error handling for ALL the database statements that can fail - connection, query, prepare, and execute, without adding more logic to your code. You currently don't have any error handling for the execute() statements (which is where a duplicate key error will occur.)
        5. If you switch to the much simpler and more consistent PDO extension, over half of the database statements will go away.
        6. Php destroys all resources created on a page when the script ends, so in most cases, you don't need to close prepared query statements or close the database connection. Your statements to do this aren't being executed anyways since they are after the point where your code is exiting.

        What you will end up with is code that -

        1. Detects that a post method form was submitted.
        2. Trims and then validates all inputs at separately. This step will actually add logic, but it makes the User eXperience (UX) better, by specifically telling the visitor what was wrong with each form field.
        3. Builds and executes an INSERT query, with exception error handling that detects if a duplicate key error occurred for the email column.
        4. If no error occurred during any of the form processing code, redirects to the exact same url of the page to cause a get request.

          At a quick glance, you probably don't want most/all of those else's anyway. That being said...

          maxie Do you have a suggestion of how I could better write this code?

          Put each self-contained task into its own, well-named function definition. Then your main block of code might look more like this (just a quick-and-dirty example):

          if(isset($_POST['submit'])) {
            if(!valid_input($_POST)) {
              // redirect to invalid input page
            }
            if(user_exists($_POST['Email'])) {
              // redirect to user taken page
            }
            create_user($_POST);
          }
          
          function valid_input($post) {
            // return true if valid, else false
          }
          
          function user_exists($email) {
            // return true if already in DB, else false
          }
          
          function create_user($post) {
            // insert into DB
          }
          

          You might also have a db_error() function that the other functions could call if something goes wrong DB-wise, which would then handle any desired logging and redirecting.

            Thank you, I will try with the functions

              Write a Reply...