0

I have a question. When you use session_start() at the beginning of the php code.

Do you keep adding the previous variables in the other forms pages?

I was thinking about using session()function for my website. It a GYM Sign UP Webpage.

It goes like this:

Homepage => Choose a trainer => choose what type of memebership to enroll => fill out form with upload picture => confirmation page

This is the trainer php code:

<?php


// Escape user inputs for security
$trainers = mysqli_real_escape_string($link, $_GET['trainers']);
$Novac = mysqli_real_escape_string($link, $_GET['Novac']);
$Urie = mysqli_real_escape_string($link, $_GET['Urie']);
$Sanni = mysqli_real_escape_string($link, $_GET['Sanni']);


// attempt insert query execution
$sql = "INSERT INTO trainers (trainers, customer_id) 
    VALUES ('$trainers', '$contactname')";
if(mysqli_query($link, $sql));


?>

Trainer's html page:

<form action='pricing.php' method='GET'>
        <div class="profile">
            <div class="profile-image">
                <a href="http://thing.cs.usm.maine.edu/~warren/mysql2/php/Tpics/blackTbigger">
                <img src="http://thing.cs.usm.maine.edu/~warren/mysql2/php/Tpics/blackT" title="" /></a>
            </div>

            <div class="profile-text">
                <p>Novac founded The Gym in 2016 with KrillaVilla and Urie.</p>
                <p><b>Novac S. Owner, Hardcore/Professional/Personal Trainer</b></p>
                                <input type="radio" name="trainers" value=" <?php echo $Novac; ?>">Novac    
        </div>
        </div>
    <div class="clearfix"></div>
        <div class="profile">
            <div class="profile-image">
                <a href="http://thing.cs.usm.maine.edu/~warren/mysql2/php/Tpics/WhiteTG_bigger">
                <img src="http://thing.cs.usm.maine.edu/~warren/mysql2/php/Tpics/WhiteTG" title=""/></a>
            </div>
            <div class="profile-text">
                <p>Urie founded The Gym in 2016 with KrillaVilla and Novac.</p>
                <p><b>-Uriena W. Assitant Owner Personal/Professional Athletes Trainer</b></p>
                  <input type="radio" name="trainers" value=" <?php echo $Urie; ?>">Urie
            </div>
        </div>
    <div class="clearfix"></div>
        <div class="profile">
            <div class="profile-image">
                <a href="http://thing.cs.usm.maine.edu/~warren/mysql2/php/Tpics/asianTbigger">
                <img src="http://thing.cs.usm.maine.edu/~warren/mysql2/php/Tpics/asianT" title=""/></a>
            </div>
            <div class="profile-text">
                <p>Krillavilla founded The Gym in 2016 with Novac and Urie.</p>
                <p><b>-KrillaVilla. Hardcore Personal Trainer/ Chief Operations Officer</b></p>
                 <input type="radio" name="trainers" value=" <?php echo $Sanni; ?>">Sanni
            </div>
        <div class="clearfix"></div>
                        <div class="clearfix"></div>  
                            <button name="Submit" type="Submit" class="subbutton"><h5>Memberships</h5></button>
                            <input type="hidden" name="Submit" id="Submit" value="true" />
                    </form> <!--- End profile Section -->
        <div class="clearfix"></div>

    </div> 

Membership php code:

<?php
// Escape user inputs for security

$membership = mysqli_real_escape_string($link, $_GET['membership']);
$trainers = mysqli_real_escape_string($link, $_GET['trainers']);
$Novac = mysqli_real_escape_string($link, $_GET['Novac']);
$Urie = mysqli_real_escape_string($link, $_GET['Urie']);
$Sanni = mysqli_real_escape_string($link, $_GET['Sanni']);




// attempt insert query execution
$sql = "INSERT INTO membership ( membership, customer_id) 
    VALUES ('$membership' ,'$contactname')";
if(mysqli_query($link, $sql));

?>

Membership html page:

<form action='contact.php' method='GET'>
            <table>
                <thead>
                <tr>
                    <th><h5>Membership Package</h5></th>
                    <th><h5>Monthly</h5></th>
                    <th><h5>Yearly</h5></th>
                    <th><h5>Selected Monthly</h5></th>
                    <th><h5>Selected Yearly</h5></th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td><h5>Bronze Package</h5></td>
                    <td><h5>$27</h5></td>
                    <td><h5>$279</h5></td>
                    <td><h5><input type="radio" name="membership" value="$27/Mo/BR">$27/Mo</h5></td>
                    <td><h5><input type="radio" name="membership" value="$279/Yr/BR">$279/Yr</h5></td>

                </tr>
                <tr>
                  <td><h5>Silver</h5></td>
                  <td><h5>$38</h5></td>
                  <td><h5>$389</h5></td>
                <td><h5><input type="radio" name="membership" value="$38/Mo/SL">$38/Mo</h5></td>
                <td><h5><input type="radio" name="membership" value="$389/Yr/SL">$389/Yr</h5></td>
                </tr>
                <tr>
                  <td><h5>Gold Package</h5></td>
                  <td><h5>$44</h5></td>
                  <td><h5>$449</h5></td>
                <td><h5><input type="radio" name="membership" value="$44/Mo/GD"> $44/Mo</h5></td>
                <td><h5><input type="radio" name="membership" value="$449/Yr/GD"> $449/Yr</h5></td>
                </tr>
                </tbody>
            </table>                            
                            <button name="Submit" type="Submit" class="subbutton"><h5>Sign Up</h5></button>
                            <input type="hidden" name="Submit" id="Submit" value=" " />
                    </form> <!--- End profile Section -->

Form php code:

<?php 
error_reporting(E_ALL ^ E_NOTICE); // hide all basic notices from PHP

//If the form is submitted
if(isset($_POST['Submit'])) {

    // require a name from user
    if(trim($_POST['contactname']) === '') {
        $nameError =  'Forgot your name!'; 
        $hasError = true;
    } else {
        $name = trim($_POST['contactname']);
    }

    // need valid email
    if(trim($_POST['email']) === '')  {
        $emailError = 'Forgot your e-mail address.';
        $hasError = true;
    } else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
        $emailError = 'Invalid email address!';
        $hasError = true;
    } else {
        $email = trim($_POST['email']);
    }

    // upon no failure errors let's email now!
    if(!isset($hasError)) {

        $emailTo = 'youremail@email.com'; // ADD YOUR EMAIL ADDRESS HERE FOR CONTACT FORM!
        $subject = 'Submitted message from '.$name; // ADD YOUR EMAIL SUBJECT LINE HERE FOR CONTACT FORM!
        $sendCopy = trim($_POST['sendCopy']);
        $body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
        $headers = 'From: ' .' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

        mail($emailTo, $subject, $body, $headers);

        // set our boolean completion value to TRUE
        $emailSent = true;
    }
    }
    ?>

<?php 

    $errors= array();
      $filename = mysqli_real_escape_string($link, $_FILES['image']['name']);
      $file_size = mysqli_real_escape_string($link, $_FILES['image']['size']);
      $filetmp =  mysqli_real_escape_string($link, $_FILES['image']['tmp_name']);
      $filetype = mysqli_real_escape_string($link, $_FILES['image']['type']);
      $file_ext=strtolower(end(explode('.', mysqli_real_escape_string($link, $_FILES['image']['name']))));

      $expensions= array("jpeg","jpg","png");

// Escape user inputs for security
$contactname =  mysqli_real_escape_string($link, $_POST['contactname']);//gender variable
$age =  mysqli_real_escape_string($link, $_POST['age']);//gender variable
$height =  mysqli_real_escape_string($link, $_POST['height']);//gender variable
$weight =  mysqli_real_escape_string($link, $_POST['weight']);//gender variable
$membership =  mysqli_real_escape_string($link, $_POST['membership']);//gender variable
$gender =  mysqli_real_escape_string($link, $_POST['gender']);//gender variable

$trainers = mysqli_real_escape_string($link, $_POST['trainers']);
$membership = mysqli_real_escape_string($link, $_POST['membership']);


if(isset($_['Submit'])){

      if(in_array($file_ext,$expensions)=== false){
         $errors[]="extension not allowed, please choose a JPEG or PNG file.";
      }

      if($file_size > 2097152) {
         $errors[]='File size must be excately 2 MB';
      }

      if(empty($errors)==true) {
         move_uploaded_file($file_tmp,"photos/".$file_name);
         echo "Success";
      }else{
         print_r($errors);
      }
    move_uploaded_file($filetmp,$file_ext);


   }

// attempt insert query execution


$sql = "INSERT INTO customer( img_id, membership_id, contactname, age, weight, height, gender, email, trainer_id) 
VALUES ('$filetmp','$membership', '$contactname','$age', '$gender', '$weight', '$height', '$email', '$trainers')";
if(mysqli_query($link, $sql));


?>

Form html code:

<div class="container content">
            <?php if(isset($emailSent) && $emailSent == true) { ?>
                <p class="info"><?php echo print_r($_POST); ?>
                        <?php echo print_r($_FILES); ?></p>
            <?php } else { ?>       
                </div>  
                <div id="contact-form">
                    <?php if(isset($hasError) || isset($captchaError) ) { ?>
                        <p class="alert">Error submitting the form</p>
                    <?php } ?>
                    <form id="contact-us" action="contact.php" method="POST" enctype = "multipart/form-data">
                        <div class="formblock">
                            <label class="screen-reader-text"><h5>Name</h5></label>
                            <input type="text" name="contactname" id="contactname" value="<?php if(isset($_POST['contactname'])) echo $_POST['contactname'];?> " class="txt requiredField" placeholder="Name:" />
                                <?php if($nameError != '') { ?>
                                <br /><span class="error"><?php echo $nameError;?></span> 
                            <?php } ?>
                            </div>

                        <div class="formblock">
                <label class="screen-reader-text"><h5>Age</h5></label>
                <input type="text" name="age" id="age" value=" " class="txt requiredField" placeholder="Age:" />    
                        </div>


                        <div class="formblock">
                <label class="screen-reader-text"><h5>Weight</h5></label>
                <input type="text" name="weight" id="weight" value=" " required=" What Your weight? " class="txt requiredField" placeholder="Weight:" />
                </div>

                        <div class="formblock">
                <label class="screen-reader-text"><h5>Height</h5></label>
                <input type="text" name="height" id="height" value=" " class="txt requiredField" placeholder="Height:" />
                    </div>

                    <div class="formblock">
                            <label class="screen-reader-text"><h5>Email</h5></label>
                            <input type="text" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" class="txt requiredField email" placeholder="Email:" />
                            <?php if($emailError != '') { ?>
                                <br /><span class="error"><?php echo $emailError;?></span>
                            <?php } ?>
                        </div>
                        <div class="clearfix"></div>


            <div class="clearfix"></div>
            <div class="formblock">
                <label class="screen-reader-text"><h5>Gender</h5>                                           
                    <input type="radio" name="gender" value="Male" class="txt requiredField" placeholder="Male"/>Male
                    <input type="radio" name="gender" value="Female" class="txt requiredField" placeholder="Female"/> Female</label>
                </div>
                                <div class="clearfix"></div>

                                                    <div class="formblock">    
                            <input type="file" name="image" value="<?php if(isset($_FILES['image']))  echo $_FILES['image'];?>" />
                            </div>

                        <div class="clearfix"></div>
                        <div class="clearfix"></div>  
                            <button name="Submit" type="Submit" class="subbutton"><h5>Submit</h5></button>
                            <input type="hidden" name="Submit" id="Submit" value="true" />      
                    </div>



                    </form> 
                    <?php } ?>


        </div>

The reason I ask because I though the session function would work better for me in this situation. Also, should I use GET instead POST to retrieve or pass the variable information through the form.

I want my confirmation page to have the user all the information they input.

Kashad
  • 19
  • 6
  • "*Do you keep adding the previous variables in the other forms pages?*" - No. That would really defeat the purpose of sessions. "*Also, should I use GET instead POST*" - Depends on what you're doing. See: http://stackoverflow.com/questions/46585/when-do-you-use-post-and-when-do-you-use-get – Mike May 09 '16 at 22:39
  • @Mike I am not using `session()` in my code i was wondering do I need to keep adding variables in forms? What I want to do to pass the data along the form until it hit a confirmation page – Kashad May 09 '16 at 22:45
  • If you're not using sessions what does `using start Session() at the beginning of the FIRST INPUT PHP FORM` mean then? – Mike May 09 '16 at 22:47
  • That what I research about `session()`, I will correct this post. they say if you want to use the `session()` function you must use it at the beginning of your page – Kashad May 09 '16 at 22:49
  • There is no such function as `session()`. I think you mean `session_start()`. You can use that function anywhere in your page, but it must be before any output is sent to the browser. That's why you usually put it right at the beginning. – Mike May 09 '16 at 22:53
  • when I declare variables for the `session_start()`. Do I need to put the variables on each webpage to retreive the information? – Kashad May 09 '16 at 22:59
  • 1
    When a webpage loads, at the top of the page the PHP script knows ***virtualy nothing about the environment it is running on***, but once you've run `session_Start();` then all values previously saved as session data (`$_SESSION['data'] = value`) will be available to that page. – Martin May 09 '16 at 23:02
  • What's your actual question? – Mike May 09 '16 at 23:47
  • @Martin if I was to pass the data in multiple forms can I do this: `$contactname = mysqli_real_escape_string($link, $_POST['contactname']);` `$_SESSION['contactname'] = "$contactname"` – Kashad May 09 '16 at 23:48
  • @Mike if I want to pass the data through multiple forms can i do this: `$contactname = mysqli_real_escape_string($link, $_POST['contactname']);` `$_SESSION['contactname'] = "$contactname"` – Kashad May 09 '16 at 23:50
  • Have you tried it? P.S. Generally you should only use `mysqli_real_escape_string()` before you execute a query. It should not be stored like that between requests. – Mike May 09 '16 at 23:55
  • @Mike I tried it and its not querying in my table in the database – Kashad May 10 '16 at 00:00
  • @Kashad What does `var_dump($_SESSION['contactname']);` output? – Mike May 10 '16 at 00:01
  • @Mike so what you saying: `$contactname = mysqli_real_escape_string($link, $_POST['contactname']);` `if(isset($_['Submit'])){ $_SESSION['contactname'] = "$contactname"; }` – Kashad May 10 '16 at 00:04
  • @Mike its grabbing the form input field `` – Kashad May 10 '16 at 00:07
  • That's not true... `$_POST['contactname']` will contain the field whose `name` attribute is `contactname`, not its `value`. Sure you don't have duplicate fields in your form? – Mike May 10 '16 at 00:32
  • @Mike Im sure I dnt have duplicate fields. I know because the data is posting on my database the problem is that customer data will post in my database but the trainers and membership data will not – Kashad May 10 '16 at 00:53
  • 1
    I'm sorry, but I can't help you. You're going to need to debug your code. You're going to have to learn to do some bug reporting. Maybe this might help: http://markonphp.com/6-debugging-tips-php-coders-should-know/ – Mike May 10 '16 at 01:16
  • Please remember that we know ***nothing*** about your issue or your code aside from what you tell us, so referencing things as "other" or using *non-absolutely-specific* language will make it up for our interpretation and therefore less accurate or missing your desired explanation. Please **edit** your question and at the bottom at a *clear and concise* summay of yur question. Thanks – Martin May 10 '16 at 07:18

1 Answers1

0

Please remember that we know nothing about your issue or your code aside from what you tell us, so referencing things as "other" or using non-absolutely-specific language will make it up for our interpretation and therefore less accurate or missing your desired explanation. Please edit your question and at the bottom at a clear and concise summay of yur question. Thanks

But, from what I think you're asking then yes, here is a logical approach.

  • On each form page you have a POST form.
  • On each following page, you then save that post data to the $_SESSION.
  • On the confirmation page you display all the recorded Session data
  • Before finally on the confirmation accepted you write the session data to the database (or file or email or whereever)

Example:

Homepage => Choose a trainer => choose what type of memebership to enroll => fill out form with upload picture => confirmation page => completion

So on the homepage:

<form method = "post">
<input name="page_1_inputname" value="whatever">
</form>

Then on the next page (Choose a trainer):

session_start(); //remember to always write this at the top of your pages

//some code here to check values are safe and valid
// You should be far more thorogh than this brief example.
$_SESSION['page_1_inputname'] = strip_tags($_POST['page_1_inputname']);
?>

<form method = "post">
<input name="page_2_inputname" value="whatever trainer">
</form>

Then on the next page:

session_start(); //remember to always write this at the top of your pages

//some code here to check values are safe and valid
// You should be far more thorogh than this brief example.
$_SESSION['page_2_inputname'] = strip_tags($_POST['page_2_inputname']);
?>

<form method = "post">
<input name="page_3_inputname" value="whatever page 3">
</form>

You should be getting the idea. Now, get to the confirmation page:

<?php 
session_start(); //never forget this at the top of your page!
?>
<div>Cofirmations:<br>
The trainer you chose is: <?php print $_SESSION['page_2_inputname'];?>
</div>

<form method='post'>
<input type="submit" name="save" value="Yes! I Confirm! Save these details"> 
</form>

Final confirmation page then:

<?php
session_start();

//somehow take each saved session element and place it in 
//the database/file or email you intend to store it in

//this structure is only for example. 
/*** 
 Works on the basis that the field names in the SESSION (and by extension 
 the HTML form are the corresonding column names for each value to be saved in 
 after confirmation.    
***/
foreach ($_SESSION as $dataKey=>$dataRow){
    $dataRow = "'".$dataRow."'"; 
    $saveData[] = "$dataRow";
    $saveKeys[] = $dataKey;
}
uset($dataKey,$dataRow);
$saveDataString = implode($saveData, ", ");
$saveKeysString = implode($saveKeys, ", "); 

$sql = "INSERT INTO table ( ".$saveKeysString.") VALUES (".$saveDataString.")";
//if(mysqli_query($link, $sql)); //this structure is bad. replace with:

if(!mysqli_query($link, $sql)) {
 $errorNotice = "Data insert failed! ".mysqli_error($link);
 }
//If you reach this point all has been saved! yay! 

PLEASE NOTE:

In a perfect world you should be using Object Orientated coding and you should be using Prepared Statements for your MySQLi database interactions.

My Database interactions detailed above are not very good and are for illustrative purposes only.

Also with multiple forms please take a serious view to considering writing code in a way and using functionality to minimise Cross Site Request Forgeries.


Final note: For form data you shold really always use POST. Get data appears on the URL line of the page, whereas POST data is stored inside the page header

Community
  • 1
  • 1
Martin
  • 22,212
  • 11
  • 70
  • 132