Jump to content

Noob - adding a new function


dslax27

Recommended Posts

Hey gang.

I'm working with a nice little multi-step form wizard from http://www.phpriot.com/articles/multi-step-wizards/1.

 

When the user completes the form, I'd like the data to be stored to a database. I added a new function called "function post2db":

 

function post2db($name, $type, $number)
        {
            // communicate with CC gateway here 		
		$user       = "root";
		$password   = "";
		$database   = "doug_db";
		$db_address = "localhost";

		$dbh = mysql_connect( $db_address, $user, $password ) or die ('I cannot connect to the database because: ' . mysql_error()); 

		$dbh = mysql_select_db( $database ) or die('cannot select db');
		//echo "<br>".$dbh;

		$submitname    = $this->getValue($form['name'], 'No Name Entered');
		$submitemail   = $this->getValue($form['email'], 'No Email Entered');
		$submitcountry = $this->getValue($form['country'], 'No Country Entered');

		$query  = "INSERT INTO dougtable (id, name, email)";
		$query .= "VALUES ('', '".$submitname."', '".$submitemail."')";

		$dbh = mysql_query( $query ) or die('failed insert query');
		//echo "<br>".$dbh;

		echo "<br><br>Your name is: ".$name;

		$dbh = mysql_close() or die('something bad happened during myqsl_close');
		}

 

You'll see that I want the data from $submitname    = $this->getValue($form['name'], 'No Name Entered'); to populate from whatever the user entered into the wizard into my database.

 

The form functions without error; however, it does not post the information to the database I created  :-\. Any ideas?

 

Here's the complete code:

 

My index.php code:

<?php
    require_once('CheckoutWizard.class.php');

    $wizard = new CheckoutWizard();
    $action = $wizard->coalesce($_GET['action']);

    $wizard->process($action, $_POST, $_SERVER['REQUEST_METHOD'] == 'POST');
        // only processes the form if it was posted. this way, we
        // can allow people to refresh the page without resubmitting
        // form data

?>
<html>
  <head>
      <title>phpRiot() wizard example</title>
  </head>
  <body>
    <h1>phpRiot() wizard example</h1>

    <?php if ($wizard->isComplete()) { ?>

      <p>
        The form is now complete. Clicking the button below will clear the container and start again.
      </p>

      <form method="post" action="<?= $_SERVER['PHP_SELF'] ?>?action=<?= $wizard->resetAction ?>">
        <input type="submit" value="Start again" />

      </form>

    <?php } else { ?>

      <form method="post" action="<?= $_SERVER['PHP_SELF'] ?>?action=<?= $wizard->getStepName() ?>">
        <h2><?= $wizard->getStepProperty('title') ?></h2>

        <?php if ($wizard->getStepName() == 'userdetails') { ?>
          <table>
            <tr>
              <td>Name:</td>
              <td>
                <input type="text" name="name" value="<?= htmlSpecialChars($wizard->getValue('name')) ?>" />
              </td>
              <td>
                <?php if ($wizard->isError('name')) { ?>
                  <?= $wizard->getError('name') ?>
                <?php } ?>
              </td>
            </tr>
            <tr>
              <td>Email:</td>
              <td>
                <input type="text" name="email" value="<?= htmlSpecialChars($wizard->getValue('email')) ?>" />
              </td>
              <td>
                <?php if ($wizard->isError('email')) { ?>
                  <?= $wizard->getError('email') ?>
                <?php } ?>
              </td>
            </tr>
            <tr>
              <td>Country:</td>
              <td>
                <select name="country">
                  <option value=""></option>
                  <?php foreach ($wizard->countries as $k => $v) { ?>
                    <option value="<?= $k ?>"<?php if ($wizard->getValue('country') == $k) { ?> selected="selected"<?php } ?>>
                      <?= $v ?>
                    </option>
                  <?php } ?>
                </select>
              </td>
              <td>
                <?php if ($wizard->isError('country')) { ?>
                  <?= $wizard->getError('country') ?>
                <?php } ?>
              </td>
            </tr>
          </table>
        <?php } else if ($wizard->getStepName() == 'billingdetails') { ?>
          <table>
            <tr>
              <td>Credit Card Type:</td>
              <td>
                <select name="cc_type">
                  <option value=""></option>
                  <?php foreach ($wizard->ccTypes as $v) { ?>
                    <option value="<?= $v ?>"<?php if ($wizard->getValue('cc_type') == $v) { ?> selected="selected"<?php } ?>>
                      <?= $v ?>
                    </option>
                  <?php } ?>
                </select>
              </td>
              <td>
                <?php if ($wizard->isError('cc_type')) { ?>
                  <?= $wizard->getError('cc_type') ?>
                <?php } ?>
              </td>
            </tr>
            <tr>
              <td>Credit Card Number:</td>
              <td>
                <input type="text" name="cc_number" value="<?= htmlSpecialChars($wizard->getValue('cc_number')) ?>" />
              </td>
              <td>
                <?php if ($wizard->isError('cc_number')) { ?>
                  <?= $wizard->getError('cc_number') ?>
                <?php } ?>
              </td>
            </tr>
          </table>
        <?php } else if ($wizard->getStepName() == 'emailconfirm') { ?>

          <p>
              Please check if you want an email confirmation:
      <input type="radio" name="emailconfirm" value="yes" checked> Yes     
      <input type="radio" name="emailconfirm" value="no">          No
          </p>

        <?php } else if ($wizard->getStepName() == 'confirm') { ?>
          <p>
              Please verify the entered details and then click next to complete your order.
          </p>

          <table>
            <tr>
              <td>Name:</td>
              <td><?= $wizard->getValue('name') ?></td>
            </tr>
            <tr>
              <td>Email:</td>
              <td><?= $wizard->getValue('email') ?></td>
            </tr>
            <tr>
              <td>Credit Card Type:</td>
              <td><?= $wizard->getValue('cc_type') ?></td>
            </tr>
            <tr>
              <td>Credit Card Number:</td>
              <td><?= $wizard->getValue('cc_number') ?></td>
            </tr>
            <tr>
              <td>Email Confirmation:</td>
              <td><?= $wizard->getValue('emailconfirm') ?></td>
            </tr>
          </table>
        <?php } ?>

        <p>
          <input type="submit" 
                 name="previous" 
                 value="<< Previous"<?php if ($wizard->isFirstStep()) { ?> disabled="disabled"<?php } ?> />
          <input type="submit" 
                 value="<?= $wizard->isLastStep() ? 'Finish' : 'Next' ?> >>" />
        </p>
      </form>
    <?php } ?>
  </body>
</html>

 

My form handler code:

<?php
    require_once('ZervWizard.class.php');

    class CheckoutWizard extends ZervWizard
    {
        function CheckoutWizard()
        {
            // start the session and initialize the wizard
            session_start();
            parent::ZervWizard($_SESSION, __CLASS__);


            // create the steps, we're only making a simple 3 step form
            $this->addStep('userdetails', 'Enter your shipping details');
            $this->addStep('billingdetails', 'Enter your billing details');
            $this->addStep('emailconfirm', 'Confirm Email Receipt');
            $this->addStep('confirm', 'Confirm your details');
        }

        // here we prepare the user details step. all we really need to
        // do for this step is generate the list of countries.

        function prepare_userdetails()
        {
            $this->loadCountries();
        }

        // now we process the first step. we've simplified things, so we're
        // only collecting, name, email address and country

        function process_userdetails(&$form)
        {
            $name = $this->coalesce($form['name']);
            if (strlen($name) > 0)
                $this->setValue('name', $name);
            else
                $this->addError('name', 'Please enter your name name');

            $email = $this->coalesce($form['email']);
            if ($this->isValidEmail($email))
                $this->setValue('email', $email);
            else
                $this->addError('email', 'Please enter a valid email address');

            $country = $this->coalesce($form['country']);
            $this->loadCountries();
            if (array_key_exists($country, $this->countries))
                $this->setValue('country', $country);
            else
                $this->addError('country', 'Please select your country');

            return !$this->isError();
        }

        // next, prepare the billing details step. again, not much to do here. here
        // we'll generate a list of the different types of credit cards

        function prepare_billingdetails()
        {
            $this->ccTypes = array('VISA', 'MASTERCARD', 'AMEX');
        }

        // the next thing we do is process the billing details step. this involves
        // validating the credit card details. we're going to use the name accepted
        // in the first step as the credit card name just to simplify things.
        // additionally, we're not going to bother with the expiry date, once again
        // just to simplify things.

        function process_billingdetails(&$form)
        {
            // load the cc types so we can validate the selected value
            $this->prepare_billingdetails();
            $cc_type = $this->coalesce($form['cc_type']);

            if (in_array($cc_type, $this->ccTypes))
                $this->setValue('cc_type', $cc_type);
            else
                $this->addError('cc_type', 'Please select a valid credit card type');

            $cc_number = $this->coalesce($form['cc_number']);

            if (strlen($cc_number) > 0 && $this->validLuhn($cc_number))
                $this->setValue('cc_number', $cc_number);
            else
                $this->addError('cc_number', 'The specified credit card number is invalid');

            return !$this->isError();
        }

// confirm if user wants an email receipt of what just happened.

        function process_emailconfirm(&$form)
        {
            $emailconfirm = $this->coalesce($form['emailconfirm'], 'no');
    $this->setValue('emailconfirm', $emailconfirm);

    // if( true )
    if( $emailconfirm == "yes" )
            {
              // send email confirmation
      // ACTUALLY don't do anything until the confirm step. This function effectively
      // does nothing.
              $this->sendUserConfirmationEmail($this->getValue('email'));
            }
     
            return !$this->isError();
        }

        // the final step is the confirmation step. there's nothing to prepare here
        // as we're just asking for final acceptance from the user

        function process_confirm(&$form)
        {
            $confirm = (bool) $this->coalesce($form['confirm'], true);

            return $confirm;
        }

        function completeCallback()
        {
            // finally, all form data is valid and the user has confirmed they
            // want to proceed. Now we do all the final processing here. Because
            // we don't really have a credit card gateway for this example we
            // just simulate it

            $this->processCreditCard($this->getValue('name'),
                                     $this->getValue('cc_type'),
                                     $this->getValue('cc_number'));


        }


        function processCreditCard($name, $type, $number)
        {
            // communicate with CC gateway here
        }

        function sendUserConfirmationEmail($email)
        {
            // create and a send an email
    $to = "test@gmail.com";
    $subject = "A Test mail";
        $theName = $this->getValue($form['name'], 'No Name Entered');
    $message = "the name entered in this form was: ".$theName;
    $from = "someonelse@example.com";
    $headers = "From: $from";
    mail($to,$subject,$message,$headers);
        }

        function post2db($name, $type, $number)
        {
            // communicate with CC gateway here 		
		$user       = "root";
		$password   = "";
		$database   = "doug_db";
		$db_address = "localhost";

		$dbh = mysql_connect( $db_address, $user, $password ) or die ('I cannot connect to the database because: ' . mysql_error()); 

		$dbh = mysql_select_db( $database ) or die('cannot select db');
		//echo "<br>".$dbh;

		$submitname    = $this->getValue($form['name'], 'No Name Entered');
		$submitemail   = $this->getValue($form['email'], 'No Email Entered');
		$submitcountry = $this->getValue($form['country'], 'No Country Entered');

		$query  = "INSERT INTO dougtable (id, name, email)";
		$query .= "VALUES ('', '".$submitname."', '".$submitemail."')";

		$dbh = mysql_query( $query ) or die('failed insert query');
		//echo "<br>".$dbh;

		echo "<br><br>Your name is: ".$name;

		$dbh = mysql_close() or die('something bad happened during myqsl_close');
		}

        /**
         * Miscellaneous utility functions
         */


        function isValidEmail($email)
        {
            return preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/i', $email);
        }

        function loadCountries()
        {
            $this->countries = array('au' => 'Australia',
                                     'de' => 'Germany',
                                     'fr' => 'France',
                                     'uk' => 'United Kingdom',
                                     'us' => 'United States');
        }

        // a method to validate a credit card number. we're not actually validating
        // it against the type of credit card, just to simplify the example. to do
        // this, it's just a matter of checking the number prefix and the length
        // of the number (depending on the card)
        function validLuhn($number)
        {
            return true;

            $len = strlen($number);
            $dbl = '';
            for ($i = $len - 2; $i >= 0; $i -= 2) {
                $dbl .= ((int) $number{$i}) * 2;
            }

            $dbllen = strlen($dbl);
            $dbltotal = 0;
            for ($i = 0; $i < $dbllen; $i++) {
                $dbltotal += (int) $dbl{$i};
            }

            $total = $dbltotal;
            for ($i = $len - 1; $i >= 0; $i -= 2) {
                $total += $number{$i};
            }
            return $total % 10 == 0;
        }
    }
?>

Link to comment
Share on other sites

Where would that global go exactly (please excuse my noobness)?

 

I tried this:

 

			$submitname    = $this->getValue(global $form['name'], 'No Name Entered');
		$submitemail   = $this->getValue(global $form['email'], 'No Email Entered');
		$submitcountry = $this->getValue(global $form['country'], 'No Country Entered');

 

but that returned with errors.

 

 

Link to comment
Share on other sites

There is no variable $form in the completeCallback() function. That's why the default values ("No name entered") are being returned. The correct way to call the getValue() function is to look for the value in the object ("this") and not in the form.

 

WRONG:

$submitname    = $this->getValue($form['name'], 'No Name Entered');

 

CORRECT:

$submitname    = $this->getValue('name', 'No Name Entered');

 

Here's the entire class (echos are removed):

<?php
    require_once('ZervWizard.class.php');

    class CheckoutWizard extends ZervWizard
    {
        function CheckoutWizard()
        {
            // start the session and initialize the wizard
            session_start();
            parent::ZervWizard($_SESSION, __CLASS__);


            // create the steps, we're only making a simple 3 step form
            $this->addStep('userdetails', 'Enter your shipping details');
            $this->addStep('billingdetails', 'Enter your billing details');
            $this->addStep('emailconfirm', 'Confirm Email Receipt');
            $this->addStep('confirm', 'Confirm your details');
        }

        // here we prepare the user details step. all we really need to
        // do for this step is generate the list of countries.

        function prepare_userdetails()
        {
            $this->loadCountries();
        }

        // now we process the first step. we've simplified things, so we're
        // only collecting, name, email address and country

        function process_userdetails(&$form)
        {
            $name = $this->coalesce($form['name']);
            if (strlen($name) > 0)
                $this->setValue('name', $name);
            else
                $this->addError('name', 'Please enter your name name');

            $email = $this->coalesce($form['email']);
            if ($this->isValidEmail($email))
                $this->setValue('email', $email);
            else
                $this->addError('email', 'Please enter a valid email address');

            $country = $this->coalesce($form['country']);
            $this->loadCountries();
            if (array_key_exists($country, $this->countries))
                $this->setValue('country', $country);
            else
                $this->addError('country', 'Please select your country');

            return !$this->isError();
        }

        // next, prepare the billing details step. again, not much to do here. here
        // we'll generate a list of the different types of credit cards

        function prepare_billingdetails()
        {
            $this->ccTypes = array('VISA', 'MASTERCARD', 'AMEX');
        }

        // the next thing we do is process the billing details step. this involves
        // validating the credit card details. we're going to use the name accepted
        // in the first step as the credit card name just to simplify things.
        // additionally, we're not going to bother with the expiry date, once again
        // just to simplify things.

        function process_billingdetails(&$form)
        {
            // load the cc types so we can validate the selected value
            $this->prepare_billingdetails();
            $cc_type = $this->coalesce($form['cc_type']);

            if (in_array($cc_type, $this->ccTypes))
                $this->setValue('cc_type', $cc_type);
            else
                $this->addError('cc_type', 'Please select a valid credit card type');

            $cc_number = $this->coalesce($form['cc_number']);

            if (strlen($cc_number) > 0 && $this->validLuhn($cc_number))
                $this->setValue('cc_number', $cc_number);
            else
                $this->addError('cc_number', 'The specified credit card number is invalid');

            return !$this->isError();
        }

// confirm if user wants an email receipt of what just happened.

        function process_emailconfirm(&$form)
        {
            $emailconfirm = $this->coalesce($form['emailconfirm'], 'no');
    $this->setValue('emailconfirm', $emailconfirm);

    // if( true )
    if( $emailconfirm == "yes" )
            {
              // send email confirmation
      // ACTUALLY don't do anything until the confirm step. This function effectively
      // does nothing.
              $this->sendUserConfirmationEmail($this->getValue('email'));
            }
     
            return !$this->isError();
        }

        // the final step is the confirmation step. there's nothing to prepare here
        // as we're just asking for final acceptance from the user

        function process_confirm(&$form)
        {
            $confirm = (bool) $this->coalesce($form['confirm'], true);

            return $confirm;
        }

        function completeCallback()
        {
            // finally, all form data is valid and the user has confirmed they
            // want to proceed. Now we do all the final processing here. Because
            // we don't really have a credit card gateway for this example we
            // just simulate it

        $user = "root";
            $password   = "";
            $database   = "doug_db";
            $db_address = "localhost";

            $dbh = mysql_connect( $db_address, $user, $password ) or die ('I cannot connect to the database because: ' . mysql_error()); 
            //echo "<br>".$dbh; // DEBUG

            $dbh = mysql_select_db( $database ) or die('cannot select db');
            //echo "<br>".$dbh; // DEBUG

            $submitname    = $this->getValue('name', 'No Name Entered');
            $submitemail   = $this->getValue('email', 'No Email Entered');
            $submitcountry = $this->getValue('country', 'No Country Entered');

            $query  = "INSERT INTO dougtable (id, name, email, country) ";
            $query .= "VALUES ('', '".$submitname."', '".$submitemail."', '".$submitcountry."')";

            $dbh = mysql_query( $query ) or die('failed insert query');
            //echo "<br>".$dbh; // DEBUG

            $dbh = mysql_close() or die('something bad happened during myqsl_close');
            //echo "<br>".$dbh; // DEBUG

        }


        function processCreditCard($name, $type, $number)
        {
            // communicate with CC gateway here
        }

        function sendUserConfirmationEmail($email)
        {
            // create and a send an email
    $to = "doug.schulkin@gmail.com";
    $subject = "A Test mail";
            $theName = $this->getValue($form['name'], 'No Name Entered');
    $message = "the name entered in this form was: ".$theName;
    $from = "someonelse@example.com";
    $headers = "From: $from";
    mail($to,$subject,$message,$headers);
        }



        /**
         * Miscellaneous utility functions
         */


        function isValidEmail($email)
        {
            return preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/i', $email);
        }

        function loadCountries()
        {
            $this->countries = array('au' => 'Australia',
                                     'de' => 'Germany',
                                     'fr' => 'France',
                                     'uk' => 'United Kingdom',
                                     'us' => 'United States');
        }

        // a method to validate a credit card number. we're not actually validating
        // it against the type of credit card, just to simplify the example. to do
        // this, it's just a matter of checking the number prefix and the length
        // of the number (depending on the card)
        function validLuhn($number)
        {
            return true;

            $len = strlen($number);
            $dbl = '';
            for ($i = $len - 2; $i >= 0; $i -= 2) {
                $dbl .= ((int) $number{$i}) * 2;
            }

            $dbllen = strlen($dbl);
            $dbltotal = 0;
            for ($i = 0; $i < $dbllen; $i++) {
                $dbltotal += (int) $dbl{$i};
            }

            $total = $dbltotal;
            for ($i = $len - 1; $i >= 0; $i -= 2) {
                $total += $number{$i};
            }
            return $total % 10 == 0;
        }
    }
?>

Link to comment
Share on other sites

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.