Jump to content

Pre-populating form from SQL using Session?


Go to solution Solved by Jacques1,

Recommended Posts

Using information that a user has already provided in their registration (and which is now in an SQL database), when the user signs in and then clicks to go to a form, I want some of the form to already be pre-populated. The log-in form is as such:

 

  <?php
    session_start();
    // check for required fields from the form
    if ((!isset($_POST['email'])) || (!isset($_POST['password']))) {
    header("Location: userlogin.html");
    exit;
    }
    //connect to server and select database
    $mysqli = mysqli_connect("localhost", "user", "password", "database")
            or die(mysqli_error());
     // use mysqli_real_escape_string to clean the input

    $email = mysqli_real_escape_string($mysqli, $_POST['email']);
    $password = mysqli_real_escape_string($mysqli, $_POST['password']);

    // Create and issue the query
    $sql = "SELECT username FROM frmak_form_1 WHERE
        email = '".$email."' AND
        password = '".$password."'";

    $result = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));

    //get the number of rows in the result set; should be 1 if a match.
    if (mysqli_num_rows($result) == 1 ) {
    // if authorized, get value of username
    while ($info = mysqli_fetch_array($result)) {
        $username = stripslashes($info['username']);
    }

     $_SESSION['user']= $info['username'];
     $_SESSION['login_until'] = time() + 60 * 60; // login expires in 1 hour

     $display_block = "<p>Welcome, ".$username."!</p>
     <br /> <br />
     <a href='submitReview.php'>Click Here to Submit a Review!</a>";
     }
     else {
    header("Location: userlogin.html");
    exit;
    }
    mysqli_close($mysqli);
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>User Login REDIRECT!!!</title>
    </head>

    <body>
        <?php echo $display_block; ?>
    </body>

    </html>






Then the "submitReview.php" file is:

   

<?php
     session_start();
     $s = &$_SESSION;    // Login status is ON and has NOT yet expired

     $isLoggedIn = isset($s['login_until']) && $s['login_until'] > time();
     if($isLoggedIn):
     $username = $s['user'];

     $s['login_until'] = time() + 60 * 60;    // extend login expiration to an hour from now.

      else
      unset($s['login_until'], $['user']);
      $username = null;

      endif;


   
      exit;
      }
      ?>

     <!DOCTYPE html>
     <html>
     <head>
     </head>
     <body>
      <p>
     <label>username</label>
     <br />
     <input name="usrnm" id="usrnm" type="text" value="<?php echo $username; ?>"/>
     <br />

     </p>
     </form>
     </body>
     </html>

In the example above, I'm only trying to display the user name in the form, because that's the only part that I want pre-populated as just a text field. The others are a radio button and a check box field, and I know those will take an even more complicated argument, so I'm just trying to make the simplest one work first.

If what I've done is not even remotely what should be done, could someone please just direct me toward a good tutorial for such things? I'm trying to teach myself PHP and MySQL, so sometimes it is a bit overwhelming. Thanks!

Time for me to learn something new perhaps.

 

Whatever does this mean?

$s = &$_SESSION;    // Login status is ON and has NOT yet expired

Ok - I did my own test (doh!) and see that you are just making a copy of session.  Why create a whole new array when you have the session one?

Edited by ginerjm

what sort of symptom or error did you get when you ran your code? you are telling us what you want to do, but didn't tell us what happened when you tried it.

 

you might also what to check back in the other php help forum where you first asked about this on 07-26-2017, so that you would benefit from information in the reply already given and the phpfreaks and S.O. forum members won't be wasting their time telling you to make the same changes to your code.

I think I have figured out partially what my problem is... my symptom is that when I click on the link to go to the "submitReview.php", it directs to that file, but nothing displays. I believe this is because I don't have it explicitly telling it to display the form... my syntax is all completely out of whack. What I am going to try next is to put in a header which directs it to a "submitReview.html" file (as opposed to PHP), but have the form in the HTML file direct back to the PHP... similar to what I have going on in the "userlogin.php" file....

don't start trying a bunch of different things as an attempt to produce working code. that will just take you a long time, approaching infinity, to accomplish anything.

 

stop and find what the actual problem is, then you can directly fix what's causing the problem.

 

you have some php syntax errors in your 2nd file. one is due to not copying the code accurately and the other is a mistake in the code that was posted.

 

if you set up your development system with php's error_reporting set to E_ALL and display_errors set to ON, in the php.ini, php will help you by reporting and displaying all the errors it detects. you may have to restart your web server to get these changes to take effect, after modifying the php.ini file. you cannot set these two settings in your code and have them report/display php syntax errors in the same file, since your code never runs when there is a php syntax error.

don't start trying a bunch of different things as an attempt to produce working code. that will just take you a long time, approaching infinity, to accomplish anything.

 

stop and find what the actual problem is, then you can directly fix what's causing the problem.

 

you have some php syntax errors in your 2nd file. one is due to not copying the code accurately and the other is a mistake in the code that was posted.

 

if you set up your development system with php's error_reporting set to E_ALL and display_errors set to ON, in the php.ini, php will help you by reporting and displaying all the errors it detects. you may have to restart your web server to get these changes to take effect, after modifying the php.ini file. you cannot set these two settings in your code and have them report/display php syntax errors in the same file, since your code never runs when there is a php syntax error

 

 

 

Thanks... I appreciate all the help that you and others in all these forums have tried to give... I think part of my problem is that I am partially not understanding the purpose of all the different pieces of code, all the functions and methods and stuff... this is largely because I'm trying to teach this to myself, and thus far, it's been in a kind of piecemeal fashion: identify one thing I want to do with PHP/mySQL, look up how to do it, do it... find some other thing.... repeat. It's really hard to kind of figure out a holistic approach to learning this.

 

All that said, I've tried to identify the first glaring thing that is going wrong, and address it... to me, that is the fact that nothing is displaying in the browser when directed toward my "submitReview" page... I realized that was because I had nothing actually telling it to display it.. I just had the HTML code but nothing to trigger it being displayed. So I changed the "submitReview.php" file to:

<?php
  session_start();
  header("Location: submitReview.html");
  exit;

  $s = &$_SESSION;    // Login status is ON and has NOT yet expired

  $isLoggedIn = isset($s['login_until']) && $s['login_until'] > time();

  if($isLoggedIn):
    $username = $s['user'];

    $s['login_until'] = time() + 60 * 60;    // extend login expiration to an hour from now. 

    else :
      unset($s, $username);
      $username = null;

    endif;


   
    exit; 
  
  ?>

  

^So this has added a header to direct it to submitReview.html, which I have changed to

<!DOCTYPE html>
<html>
<head>
 <title>Submit a Review</title>
</head>
<body>

<?php session_start(); ?>
<p>Hey, <?php echo $username ?> !!!!! </p><!-- just trying to see if the document will recognize the variable --> 


<form method="post" action="submitReview.php">


    <p style="">
      <label style="font-size:1.2em; font-weight:bold;">name</label>
      <br>
      <input class=" w3-border w3-round-large" name="username" type="text" value="<?php echo $username; ?>"
      size="35" style="padding:8px; "></p>
    </p>


</form>
</body>
</html>

Am I even close to being on the right track? I just... can someone point me to another resource, to help me understand my problem better? Thanks!!!

  • Solution

The real problem is that you're jumping to advanced tasks before you've fully understood the basics, and you start writing code before you've finished the concept.

 

Learn the PHP basics first. Learn how to safely query the database with PDO and prepared statements. Learn the basics of security like HTML-escaping and password hashing. And most importantly: Actually think about what you're doing, don't just blindly copy and paste code you've found somewhere on the Internet. Does it really make sense to print internal error message on the website? Attackers will surely find this information useful, but legitimate users cannot do anything with it and will probably wonder what the hell is going on. Does it really make sense to repeatedly fetch rows with a loop when you know there's exactly one row?

 

Start small and build your application from the ground up. Simply copying and pasting code fragments may yield quick results at first, but what's the point of all that code when most of it is garbage and you have no idea what it even does?

 

Secondly, make a plan before you start typing. You don't need walls of diagrams, but you should at least have a basic idea of where this is going. Trial and error doesn't work. Why do you even want to insert the username into a form field? Do you want the user to change it and submit the review under a different name? What's the point of that?

  • Like 1

You're pretty much spot-on, Jacques... I think I was trying to do something a bit more complicated than I was used to, and I was trying to rely solely on copying and pasting bits of code... Plus, I had tried so many things, and had so much going on there, that it made no sense. I scrapped it all, and started from scratch... I started a session at the top of the user login form, and declared session variables for the user name and the email. For this first phase, I just made them a string literal... I then made the "submitReview.php" file simply start (or really, continue) the session, and made it a simple block of html which called up the Session variables in the context of a <p> tag-- this first step was just to confirm that I was, indeed successfully starting the session, and that the variables were being passed. When this succeeded (and it did!), I went and instead of  calling them up in a <p> tag, I went and made the (very basic) form, and placed the variables in the "value" part:

<p>
      <label style="font-size:1.2em; font-weight:bold;">user name</label> <br>
      <input class=" w3-border w3-round-large" name="usrname" id="usrname" type="text" size="35" style="padding:8px;" value="<?php echo $_SESSION['user']; ?>">
    </p>

Lo and behold, it actually worked!!!! Like I said, I had such a tangled mess of nonsensical code, that it was impossible for me to try and just "fix" what was there, so I started from scratch. I think one of the things that was wrong is that I was missing some quotation marks in a couple of places.

 

To answer one of your questions, though, as to why I would want to insert a username into the form field, it's like: this particular form will have many fields, but the first few are in order to associate entry with a particular user... basically doing a JOIN ON 'username' type deal... And so if a user is already logged in, and starts to fill out this form, they don't have to fill in their name, email address, etc, because by simply being signed in, the form will know all that info about them.

My point is: The form shouldn't contain the username at all. The session alone tells you who the user is. Carrying the username around is not only superfluous, it's absolutely wrong, because the user may willingly or accidently change that field and break your lookup system. What if I enter the name of somebody else? Does that allow me to forge reviews? What if I enter a nonsense name?

 

The whole session approach doesn't make much sense. If you have a log-in system with an underlying database, then the session shouldn't contain anything but the user ID. That's how you reference the user. Names, e-mail addresses etc. should stay in the database.

 

Besides that, you definitely need to work on your HTML. Escape PHP variables before you insert them. Avoid this inline CSS mess and write clean semantic markup.

 

I'm glad to hear that you've scrapped the previous code, but there's still a lot to learn. Just because the code seemingly "works" doesn't mean it's actually valid.

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.