If statement not fully functional?

Yes I placed them underneath all of the other PHP code. Underneath that is just my three forms. How can I display all the errors you are seeing? Will I only see them if they’re on a live server? I am using a localhost wampserver and have error_reporting(E_ALL); set at the top of my page as well.

I have updated the preferences.php page on the github project here.

Ok. I managed to get it to display. But you really need to clean your codes. alias was also returning nothing because when you log in, alias is set to have email’s value. In the preference page, you tried to grab alias’s column using the alias session. The alias session contains the email. So in this case, you are selecting the wrong column.

Next, let’s address your issue. Your issue is that your checker was within the if (isset($_POST['delete-account'])) { statement which in this case returns false since it was never really submitted through that form. You only tried to link this from within the if (isset($_POST['delete_account'])) { statement. This also means that since you have a new form for the 2 buttons, they won’t do anything other than go straight back to the preference page and display nothing because again, your checker is within if (isset($_POST['delete_account'])) { which also means that it will never be called because if (isset($_POST['delete_account'])) { was never set when you clicked on the two buttons. The two buttons don’t have an action so it would default to the current page it is on. It also will not bring anything else that pertains to if (isset($_POST['delete_account'])) { with it.

Now let’s address the more serious issue. While going through your codes, I notice that you keep placing them at the far far bottom of the page. You should not be doing this. If you turn error logs on through your PHP installation, you will find that you will get a lot of headers already sent error. This means you are outputting HTML stuff before header(). You cannot do this because it violates HTTP 1.1. You must adhere to the rules of HTTP 1.1 which is doing your header() stuff before you output.

All of my pages are start with

include 'core/common.inc.php';
showHeader('Preferences');

They include the core/common.inc.php file to get all of my functions that I have setup in that file and then the showHeader() function sets up all of the titles, stylesheets and starting tags that should start at the beginning of each page as you can see below:
https://puu.sh/Ab9KS/a44c98d026.png

As for all of the errors that you see and I don’t, I have my WAMPserver setup correctly as far as I know because in my php.ini file I have error_reporting set to E_ALL. I am not sure why I am not seeing as many errors as you are.

I think my best bet for the form as of right now is just restarting the delete account form and start fresh regarding that because its clear I messed something up along the way of creating all those button(s) and input(s) in multiple different forms and trying to use them in the same statement.

UPDATE: I figured out a new method to use another form to delete users account as you can see on the updated github repository here. Although I figured it out I am still interested in figuring out where the error(s) that you’re getting are coming from because I do have my WAMPserver setup correctly and am not getting any sort of errors anywhere.

I personally wouldn’t do it that way. I’d make my life a little easier by doing separation of logic. This is a way to make things easier. You separate your files based on action and require only what is needed. This way, you don’t get all this junk sitting in the way.

2 Likes

Are you speaking of the showHeader() function?!

No. I am talking about logic as in how you do things and place things. The reason why yours isn’t working the way you want it to is because your logic is flawed. The way you setup your files makes it hard for yourself to follow. I don’t know if this term exists, but I call it “Separation of Logic”. What this triesti achieve is break things down in a much easier way for yourself to follow and understand.

For instance, say I have an index page. I don’t want anything in there except just a landing screen. Therefore, there is no need for a form submission check. So I would move to the next following concept. If my index page requires data from the database and doesn’t require user input, then I would create 2 files. One file to place all my variables in and one file for my HTML. The actual index.php page will act as my controller. My second file will act as my presentation. This will help separate each logic in a way that it “tries” to mimic MVC, but isn’t exactly an MVC application. This way, when I do happen to want to learn MVC, I can apply these logic that I have conditioned myself to learn and make the swap from procedural to MVC. It is also a good way to organize my codes in a way I can follow and understand.

That is why I keep referring to “logic”. Because “logic” is what tells who a person is by the way they think. If your logic is flawed then the way you are thinking and setting up your files is also flawed.

4 Likes

I agree with spaceshiptrooper. This is all really sloppy and messy. Short of implementing OO programming and MVC I don’t know what I would recommend. Separation of concerns is a fundamental concept in software architecture. I really hate to recommend CodeIgniter because I think that framework is a huge piece of sh*t but for a beginner not familiar with OOP and MVC it might be worth checking out. Laravel is my preferred PHP framework but it has a huge learning curve to something lightweight with low levels of abstraction like CodeIgniter.

2 Likes

OK I appreciate the feedback! How would I go about using something like CodeIgniter that ZooKeeper recommended to get the “Seperation of Logic”?

I wouldn’t recommend CodeIgniter just yet. If you don’t understand OO yet, it is going to be super hard for you to use CodeIgniter because the entire use is in OO. Instead, what I am proposing is a way to separate your stuff in a way that it “kind of” acts like MVC or the idea anyways.

Take this simple sample snippet for example.

<?php
$variable = 'This variable contains some random information that should be passed down.';

require_once('index_view.php');
<!DOCTYPE html>
<html>
<head>
<title>Here is a random file</title>
</head>

<body>
<h1>Welcome!</h1>
<p>Tell me what is in the <strong>$variable</strong> variable.
<pre><?php print($variable); ?></pre>
</body>
</html>

The first snippet should be where the user lands. So if it was the index page, the first snippet would be called index.php. So what this really achieves is that it makes everything easier for you to read. Do you see the difference between yours and this snippet? I’m also not talking about length wise. I am talking about readability.

The index.php file acts like a controller and “tries” to mimic the idea of MVC, but it isn’t actually MVC at all. By doing this, you separate your business logic from your presentation. I am assuming you don’t know the ideology of MVC. MVC is just a way to separate your logic. There are 3 parts to this ideology. M stands for Models which should only contain your database stuff. V stands for Views which contains your presentation or your visual stuff. So in your views, you’ll mostly see a lot of HTML stuff. And C stands for Controllers which is the main place you’ll be doing your processing. You could put PHP code in your Views if you want, but you want to limit the amount of PHP codes that go into your Views. If you have data processing, that should never go in your views, this should actually be in your controllers.

So why am I telling you this? Because the way I am proposing to you now “tries” to mimic this in a procedural way. Short of it using OO and re-usability, it in a way does feel like MVC. That is the only reason why I mentioned MVC to you. Otherwise, I wouldn’t because you don’t understand basic logic yet. Jumping right into MVC will confuse you so much more.

You may think that this way is redundant or unnecessary, but it actually isn’t. By doing it this way, you allow yourself the ability to maintain clean code and you allow yourself to work in a logic flow that is easy for you to follow.

Let’s take another simple sample snippet for example.

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {

	// Let's do our validations here.
	print_r($_POST);

} else {

	$variable = 'This variable contains some random information that should be passed down.';

	require_once('index_view.php');

}
<!DOCTYPE html>
<html>
<head>
<title>Here is a random file</title>
</head>

<body>
<h1>Welcome!</h1>
<p>Tell me what is in the <strong>$variable</strong> variable.
<pre><?php print($variable); ?></pre>
<form action="" method="POST">
	<input type="text" name="random" placeholder="Random" autocomplete="off"><br>
	<button type="text">Submit</button>
</form>
</body>
</html>

So in these two snippets, we are processing user input. All we have actually done that’s different from the first 2 sample snippet is adding in a form. The idea is the same. We use the first sample snippet as a controller. The first step we do is check to see if the page was requested via POST. If it isn’t, then we will include our index_view.php file. If the form was submitted, we then do a print_r($_POST) to display what was posted. You usually don’t want to output anything in your controllers. That should always be handled by your Views.


So why is this important to your problem? Because again, it relates to your logic. The reason why you aren’t getting the results you want is because of the way you set your codes up. You are using a bunch of random functions that really are unnecessary. Functions should really only be used for returning data or doing something in pure PHP. If all you are trying to do is include the header. You could simply do this by including it using require or include. It’s that simple.

There are a lot of other things that is wrong with your code, but one step at a time.

3 Likes

OK thank you for being so helpful with your tips! I am trying to use the format you gave me to maintain the same type of format you’re using to sort the code but ran into an issue while doing so. I have my index.php for my models page to put my database stuff as well as my controller page for all my php stuff and my index_view.php as my views page where all my presentation and visual stuff.

index.php:

<?php
// if user post (submits a form)
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $alias = $_POST['alias'];
    //$password = $_POST['password'];

    $servername = 'localhost';
    $db_name = 'registration';
    $db_user = 'root';
    $db_pw = '';
    
    try {
        $conn = new PDO("mysql:host=$servername;dbname=$db_name", $db_user, $db_pw);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $conn->prepare("SELECT password, activated FROM users WHERE alias = :alias");
        $stmt->bindParam(':alias', $alias);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
    }
    catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    
    if ($result != null) {echo 'something found!';} else {echo 'nothing found.';}
    
    
// if user hasn't submit form, show them regular index_view.php page 
} else {
    
    $variable = 'This variable contains some random information that should be passed down.';
    require_once('index_view.php');
    
}

?>

index_view.php:

<!DOCTYPE html>
<html lang="en">
    
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta name="google-signin-client_id" content="618381226281-f3ht6d47jl818rjmr0p3rh3idftoaka7.apps.googleusercontent.com"/>
    <link rel="stylesheet" href="includes/main_stylesheet.css" type="text/css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://www.google.com/recaptcha/api.js"></script>
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    <title>HeartFX homepage</title>
</head>

<body>
    
<form method="post">
    <input type="text" name="alias" placeholder="username" class="half">
    <button type="submit" class="signin_button">sign in</button>
</form>
    
</body>

The issue is that whenever I try to run a username in the form that exists in the database it still continues to {echo 'nothing found.';}. I tried to run a dbConnect() function inside of following line of code:

if($_SERVER['REQUEST_METHOD'] == 'POST') {

but that was also a dead end. I made sure my database was connecting successfully, I’m unsure what is causing this to happen.

It works for me. I don’t know why it isn’t working for you.







Look at your registration table again and look at what you have in your rows.

That feeling when you’ve been looking at the wrong database the entire time :banghead: :lol:

2 Likes

So besides the issue I had with the database, is that the layout that each page should be layed out like? Also will I now need two different pages to function one. Do you recommend the views pages all in one folder together and call them from something like views/index_view.php?

Also, I am not sure why but my styles aren’t working on what is in my index.php page as far as the user echo statements I have under the controllers. For example:

if ($result == null) {
    echo '<p class="input_error">'.$alias.' is not affiliated with a registered account.</p>';
}

in my includes/css.css file it should set the color of the text to #a93b3d but nothing changes. Whats happening is the page just echo’s the text. I am not sure how to go about fixing it so I can control the looks of it in the stylesheet but when I inspect the raw code of the page it just prints <p class="input_error">test is not affiliated with a registered account.</p> like this:

https://puu.sh/AcrSt/884c3e73b5.png

Yup. It should be able to help you with organizations. I know that I’ve shown this layout to @lurtnowski before. I’m not sure if he likes this, but I do see him using it often.

Yes. That is the point of this “Separation of Logic” idea. It’s to help you organize and write code better.

Yes. You could have them in separate folders if you remember to call them from the correct location.

Your styles aren’t working because this no longer uses what you had before. You will have to include the header file inside your Views or require it via the main file.

1 Like

Would it be okay to put a controller in the views page?! I’m not sure of any other way to check if $_SESSION[;'alias'] isset. I need to check if $_SESSION['alias'] isset so I can determine rather or not to show the sign in form or the signed in module where it’ll show users avatar, preferences page, and sign out button.

No. That would break this rule. The whole entire idea is to separate everything that’s PHP heavy to it’s own file and just leaving the HTML stuff for you to work with. What I suggest is creating another file to place all the HTML stuff in if it’s going to be used more than a few times. Then you just do an if(isset($_SESSION['alias'])) in your Views. Then inside that if statement, you can then just require the other HTML file. If you place your HTML element’s in your Controller, this will violate this rule and there would be no point using this system.

Also, just to be clear, this is not an actual MVC application and will not function like one. All we are doing is adopting the idea of separating our files based on action so that it’ll be a lot easier for us to work with than mashing everything all in one file.

1 Like

OK I am currently using my index_view.php page to put all of my HTML stuff and my controllers & models are in my index.php page.

#index.php

<?php
/*
	 ////////////////
	// OLD LAYOUT //
	///////////////
	include 'core/common.inc.php';
	// includes header
	showHeader('Home');

	// show login module
	loginModule();
*/
// if user post (submits a form method="post")
function redirect($page) {
	header('refresh:3; url=' . $page);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	function dbConnect() {
	    // configuration
	    $server_name = 'localhost';
	    $db_name = 'registration';
	    $dbuser = 'root';
	    $dbpw = '';
	    // connect to database
	    try{
	        $conn = new pdo("mysql:host=$server_name;dbname=$db_name;", $dbuser, $dbpw);
	        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	        return $conn;

	    }   catch(PDOException $e){
	        echo 'ERROR', $e->getMessage();
	    }
	}

	$alias = $_POST['alias'];
	$password = $_POST['password'];

	$query = dbConnect()->prepare("SELECT password, activated FROM users WHERE alias = :alias");
	$query->bindParam(':alias', $alias);
	$query->execute();
	$result = $query->fetch(PDO::FETCH_ASSOC);

	// so that the p classes are communicating with the stylesheet!
	require 'views/index_view.php';

	// check for errors

	// if no info comes back from database with $alias, give user error
	if ($result == null) {
		echo '<p class="input_error">'.$alias.' is not affiliated with a registered account.</p>';
	// if email address is not verified, give user error
	} elseif ($result['activated'] != '1') {
		echo '<p class="input_info">email is not verified.</p>';

	// else sign in
	} else {
		$storedHash = $result['password'];
		if (password_verify($password, $storedHash)) {
			// set $_session['alias']
			$_SESSION['alias'] = $alias;
			echo '<p class="input_success">login successful</p>';
			redirect('index.php');
		} else {
			echo '<p class="input_error">password invalid</p>';
		}
	}

} else {
	require('views/index_view.php');
}
?>

#index_view.php

<html lang="en">
  <head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta name="google-signin-client_id" content="618381226281-f3ht6d47jl818rjmr0p3rh3idftoaka7.apps.googleusercontent.com"/>
    <link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet"/>
    <link rel="stylesheet" href="includes/css.css" type="text/css"/>
    <link rel="stylesheet" href="includes/media_queries.css" type="text/css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://www.google.com/recaptcha/api.js"></script>
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    <title>Homepage</title>
  </head>

  <body>
    <form method="post" id="signin-form">
        <input type="text" name="alias" placeholder="username or email address" class="half">
        <input type="password" name="password" placeholder="password" maxlength="18" class="half">

        <div class="login_form_bottom">
          <input type="checkbox" name="remember">remember me</input>
          <a style="float:right;" href="forgot_password.php">forgot password?</a>
        <div>

          <button type="submit" class="signin-button"><strong>sign in</strong></button><br />
          <p style="margin-top:-5px;" class="register-heading"><a href="forgot_password.php">Forgot password?</a></p>
          <p class="register-heading">Not registered? <a class="create-account" href="register.php">Create an account</a></p>
    </form>
  </body>
</html>

I wasn’t thinking of putting any html in my controller page (index.php) but possibly adding one line of php into my views to check if (isset($_SESSION['alias'])) - something like this possibly?!
#index_view.php

if (isset($_SESSION['alias'])) {
  // show signed in module (user avatar, preferences, sign off)
} else {
  // show sign in form
}

Not sure how to do it any other way without breaking some sort of rule in the controller or views page.

This doesn’t need to be a function. Just place it inside a file and then require it when you want to use the database connection.

This file should actually be named different so that you don’t re-use the same exact default file. If the user doesn’t submit the form, it’ll default to a page where they are asked to input in their credentials and then it’ll submit the form. The first part is to process the data and redirect accordingly.

Again, you seem to fail to understand this whole logic/system. You are doing exactly what I am telling you not to do. All of your HTML stuff should be in your Views. If the results don’t show anything, use a $_SESSION cookie and redirect them back to the form page and within the HTML of that form page, you can then check to see if that $_SESSION cookie exists. If it does, then display these errors.


Also, this is wrong. Again, you are doing exactly what I am telling you not to do. You are using the header() function at the bottom of your output. This will display that Headers already sent error that you can’t see because you never turned on your error logs.

Alright, sorry about that didn’t mean to put the html there in my controller page but not sure how else to echo errors within an else/if statement. Also, I am not sure what I am doing wrong that I’m not seeing any error log(s). I have it setup correctly in my wampserver php.ini. I fixed the database function so now I have file at core/db.php that looks like:
#core/db.php

<?php
// configuration
$server_name = 'localhost';
$db_name = 'registration';
$dbuser = 'root';
$dbpw = '';
// connect to database
try{
    $conn = new pdo("mysql:host=$server_name;dbname=$db_name;", $dbuser, $dbpw);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $conn;

}   catch(PDOException $e){
    echo 'ERROR', $e->getMessage();
}
?>

Instead of having the function there I now am just using require 'core/db.php' where the function originally was.


Should I simply put just the form that is displayed when user is not signed in and have another page for what the user will see when they are actually logged in? Just a bit confused as to how I am going to use the one page to determine what form they are seeing without using php in my views page :slight_frown:

1 Like

Good. Now you’re getting the hang of it. This is a good start.

Use this as an example.

<?php
session_start();
require_once('core/db.php');

if($_SERVER['REQUEST_METHOD'] == 'POST') {

	// If all we are doing is checking to see if the user's account exists, the we can just do something like this.
	$results = ...

	if($results) {

		// User exists, set a session cookie and redirect back to the index page.
		$_SESSION['alias'] = ...

		redirect('index.php');

		// This will be another new page that will require the stylesheets
		// Infact, let's just do it like so.
		require_once('header_styles.php');
		require_once('index_login_message.php');

	} else {

		// The user doesn't exist, let's redirect them back.
		redirect('index.php');

		require_once('index_login_bad_account_message.php');

	}

} else {

	if(isset($_SESSION['alias'])) {

		// Do the database stuff.

		$results = ...

		require_once('index_logged_in_view.php');

	} else {

		require_once('index_view.php');

	}

}

Then I would create 2 separate files for the index page. One for the logged in user and one for the logged out user. Like so.

<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>

<body>
Our form here. The user is not logged in.
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>

<body>
<h1>Welcome <?php print($results['name']); ?></h1>
<?php require_once('account_info.php'); ?>
</body>
</html>

Something similar to this. Don’t use the exact sample since $results in the the first snippet will not work since it has ... after it. I am doing this as an example. Do you see that in the first snippet, there’s no actual echoing anything?

1 Like