abs0lut Posted October 22, 2008 Share Posted October 22, 2008 validate.php <?php // start PHP session session_start(); // load error handling script and validation class require_once ('error_handler.php'); require_once ('validate.class.php'); // Create new validator object $validator = new Validate(); // read validation type (PHP or AJAX?) $validationType = ''; if (isset($_GET['validationType'])) { $validationType = $_GET['validationType']; } // AJAX validation or PHP validation? if ($validationType == 'php') { // PHP validation is performed by the ValidatePHP method, which returns // the page the visitor should be redirected to (which is allok.php if // all the data is valid, or back to index.php if not) $username=$_POST['txtUsername']; $email=$_POST['txtEmail']; // check if the username exists in the database //$query2 = mysql_query("INSERT INTO users (user_name, Email) VALUES ('".$_POST['txtUsername']."','".$_POST['txtEmail']".')") or die(mysql_error()); $query2 = $validator->mMysqli->query("INSERT INTO users (user_name, Email) VALUES ('$username','$email')"); header("Location:" . $validator->ValidatePHP()); } else { // AJAX validation is performed by the ValidateAJAX method. The results // are used to form an XML document that is sent back to the client $response = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . '<response>' . '<result>' . $validator->ValidateAJAX($_POST['inputValue'], $_POST['fieldID']) . '</result>' . '<fieldid>' . $_POST['fieldID'] . '</fieldid>' . '</response>'; // generate the response if(ob_get_length()) ob_clean(); header('Content-Type: text/xml'); echo $response; } ?> validate.class.php <?php require_once ('config.php'); // Class supports AJAX and PHP web form validation class Validate { // stored database connection private $mMysqli; // constructor opens database connection function __construct() { $this->mMysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE); } // destructor closes database connection function __destruct() { $this->mMysqli->close(); } // supports AJAX validation, verifies a single value public function ValidateAJAX($inputValue, $fieldID) { // check which field is being validated and perform validation switch($fieldID) { // Check if the username is valid case 'txtUsername': return $this->validateUserName($inputValue); break; // Check if the name is valid case 'txtName': return $this->validateName($inputValue); break; // Check if a gender was selected case 'selGender': return $this->validateGender($inputValue); break; // Check if birth month is valid case 'selBthMonth': return $this->validateBirthMonth($inputValue); break; // Check if birth day is valid case 'txtBthDay': return $this->validateBirthDay($inputValue); break; // Check if birth year is valid case 'txtBthYear': return $this->validateBirthYear($inputValue); break; // Check if email is valid case 'txtEmail': return $this->validateEmail($inputValue); break; // Check if phone is valid case 'txtPhone': return $this->validatePhone($inputValue); break; // Check if "I have read the terms" checkbox has been checked case 'chkReadTerms': return $this->validateReadTerms($inputValue); break; } } // validates all form fields on form submit public function ValidatePHP() { // error flag, becomes 1 when errors are found. $errorsExist = 0; // clears the errors session flag if (isset($_SESSION['errors'])) unset($_SESSION['errors']); // By default all fields are considered valid $_SESSION['errors']['txtUsername'] = 'hidden'; $_SESSION['errors']['txtName'] = 'hidden'; $_SESSION['errors']['selGender'] = 'hidden'; $_SESSION['errors']['selBthMonth'] = 'hidden'; $_SESSION['errors']['txtBthDay'] = 'hidden'; $_SESSION['errors']['txtBthYear'] = 'hidden'; $_SESSION['errors']['txtEmail'] = 'hidden'; $_SESSION['errors']['txtPhone'] = 'hidden'; $_SESSION['errors']['chkReadTerms'] = 'hidden'; // Validate username if (!$this->validateUserName($_POST['txtUsername'])) { $_SESSION['errors']['txtUsername'] = 'error'; $errorsExist = 1; } // Validate name if (!$this->validateName($_POST['txtName'])) { $_SESSION['errors']['txtName'] = 'error'; $errorsExist = 1; } // Validate gender if (!$this->validateGender($_POST['selGender'])) { $_SESSION['errors']['selGender'] = 'error'; $errorsExist = 1; } // Validate birth month if (!$this->validateBirthMonth($_POST['selBthMonth'])) { $_SESSION['errors']['selBthMonth'] = 'error'; $errorsExist = 1; } // Validate birth day if (!$this->validateBirthDay($_POST['txtBthDay'])) { $_SESSION['errors']['txtBthDay'] = 'error'; $errorsExist = 1; } // Validate birth year and date if (!$this->validateBirthYear($_POST['selBthMonth'] . '#' . $_POST['txtBthDay'] . '#' . $_POST['txtBthYear'])) { $_SESSION['errors']['txtBthYear'] = 'error'; $errorsExist = 1; } // Validate email if (!$this->validateEmail($_POST['txtEmail'])) { $_SESSION['errors']['txtEmail'] = 'error'; $errorsExist = 1; } // Validate phone if (!$this->validatePhone($_POST['txtPhone'])) { $_SESSION['errors']['txtPhone'] = 'error'; $errorsExist = 1; } // Validate read terms if (!isset($_POST['chkReadTerms']) || !$this->validateReadTerms($_POST['chkReadTerms'])) { $_SESSION['errors']['chkReadTerms'] = 'error'; $_SESSION['values']['chkReadTerms'] = ''; $errorsExist = 1; } // If no errors are found, point to a successful validation page if ($errorsExist == 0) { return 'allok.php'; } else { // If errors are found, save current user input foreach ($_POST as $key => $value) { $_SESSION['values'][$key] = $_POST[$key]; } return 'index.php'; } } // validate user name (must be empty, and must not be already registered) private function validateUserName($value) { // trim and escape input value $value = $this->mMysqli->real_escape_string(trim($value)); // empty user name is not valid if ($value == null) return 0; // not valid // check if the username exists in the database $query = $this->mMysqli->query('SELECT user_name FROM users ' . 'WHERE user_name="' . $value . '"'); if ($this->mMysqli->affected_rows > 0) return '0'; // not valid else return '1'; // valid } // validate name private function validateName($value) { // trim and escape input value $value = trim($value); // empty user name is not valid if ($value) return 1; // valid else return 0; // not valid } // validate gender private function validateGender($value) { // user must have a gender return ($value == '0') ? 0 : 1; } // validate birth month private function validateBirthMonth($value) { // month must be non-null, and between 1 and 12 return ($value == '' || $value > 12 || $value < 1) ? 0 : 1; } // validate birth day private function validateBirthDay($value) { // day must be non-null, and between 1 and 31 return ($value == '' || $value > 31 || $value < 1) ? 0 : 1; } // validate birth year and the whole date private function validateBirthYear($value) { // valid birth year is between 1900 and 2000 // get whole date (mm#dd#yyyy) $date = explode('#', $value); // date can't be valid if there is no day, month, or year if (!$date[0]) return 0; if (!$date[1] || !is_numeric($date[1])) return 0; if (!$date[2] || !is_numeric($date[2])) return 0; // check the date return (checkdate($date[0], $date[1], $date[2])) ? 1 : 0; } // validate email private function validateEmail($value) { // valid email formats: *@*.*, *@*.*.*, *.*@*.*, *.*@*.*.*) return (!eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$', $value)) ? 0 : 1; } // validate phone private function validatePhone($value) { // valid phone format: ###-###-#### return (!eregi('^[0-9]{3}-*[0-9]{3}-*[0-9]{4}$', $value)) ? 0 : 1; } // check the user has read the terms of use private function validateReadTerms($value) { // valid value is 'true' return ($value == 'true' || $value == 'on') ? 1 : 0; } } ?> index.php <?php require_once ('index_top.php'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Practical AJAX: Form Validation</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="validate.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="validate.js"></script> </head> <body onload="setFocus();"> <fieldset> <legend class="txtFormLegend">New User Registration Form</legend> <br /> <form name="frmRegistration" method="post" action="validate.php?validationType=php"> <!-- Username --> <label for="txtUsername">Desired username:</label> <input id="txtUsername" name="txtUsername" type="text" onblur="validate(this.value, this.id)" value="<?php echo $_SESSION['values']['txtUsername'] ?>" /> <span id="txtUsernameFailed" class="<?php echo $_SESSION['errors']['txtUsername'] ?>"> This username is in use, or empty username field. </span> <br /> <!-- Name --> <label for="txtName">Your name:</label> <input id="txtName" name="txtName" type="text" onblur="validate(this.value, this.id)" value="<?php echo $_SESSION['values']['txtName'] ?>" /> <span id="txtNameFailed" class="<?php echo $_SESSION['errors']['txtName'] ?>"> Please enter your name. </span> <br /> <!-- Gender --> <label for="selGender">Gender:</label> <select name="selGender" id="selGender" onblur="validate(this.value, this.id)"> <?php buildOptions($genderOptions, $_SESSION['values']['selGender']); ?> </select> <span id="selGenderFailed" class="<?php echo $_SESSION['errors']['selGender'] ?>"> Please select your gender. </span> <br /> <!-- Birthday --> <label for="selBthMonth">Birthday:</label> <!-- Month --> <select name="selBthMonth" id="selBthMonth" onblur="validate(this.value, this.id)"> <?php buildOptions($monthOptions, $_SESSION['values']['selBthMonth']); ?> </select> - <!-- Day --> <input type="text" name="txtBthDay" id="txtBthDay" maxlength="2" size="2" onblur="validate(this.value, this.id)" value="<?php echo $_SESSION['values']['txtBthDay'] ?>" /> - <!-- Year --> <input type="text" name="txtBthYear" id="txtBthYear" maxlength="4" size="2" onblur="validate(document.getElementById('selBthMonth').options[document.getElementById('selBthMonth').selectedIndex].value + '#' + document.getElementById('txtBthDay').value + '#' + this.value, this.id)" value="<?php echo $_SESSION['values']['txtBthYear'] ?>" /> <!-- Month, Day, Year validation --> <span id="selBthMonthFailed" class="<?php echo $_SESSION['errors']['selBthMonth'] ?>"> Please select your birth month. </span> <span id="txtBthDayFailed" class="<?php echo $_SESSION['errors']['txtBthDay'] ?>"> Please enter your birth day. </span> <span id="txtBthYearFailed" class="<?php echo $_SESSION['errors']['txtBthYear'] ?>"> Please enter a valid date. </span> <br /> <!-- Email --> <label for="txtEmail">E-mail:</label> <input id="txtEmail" name="txtEmail" type="text" onblur="validate(this.value, this.id)" value="<?php echo $_SESSION['values']['txtEmail'] ?>" /> <span id="txtEmailFailed" class="<?php echo $_SESSION['errors']['txtEmail'] ?>"> Invalid e-mail address. </span> <br /> <!-- Phone number --> <label for="txtPhone">Phone number:</label> <input id="txtPhone" name="txtPhone" type="text" onblur="validate(this.value, this.id)" value="<?php echo $_SESSION['values']['txtPhone'] ?>" /> <span id="txtPhoneFailed" class="<?php echo $_SESSION['errors']['txtPhone'] ?>"> Please insert a valid US phone number (xxx-xxx-xxxx). </span> <br /> <!-- Read terms checkbox --> <input type="checkbox" id="chkReadTerms" name="chkReadTerms" class="left" onblur="validate(this.checked, this.id)" <?php if ($_SESSION['values']['chkReadTerms'] == 'on') echo 'checked="checked"' ?> /> I've read the Terms of Use <span id="chkReadTermsFailed" class="<?php echo $_SESSION['errors']['chkReadTerms'] ?>"> Please make sure you read the Terms of Use. </span> <!-- End of form --> <hr /> <span class="txtSmall">Note: All fields are required.</span> <br /><br /> <input type="submit" name="submitbutton" value="Register" class="left button" /> </form> </fieldset> </body> </html> index_top.php <?php // enable PHP session session_start(); // Build HTML <option> tags function buildOptions($options, $selectedOption) { foreach ($options as $value => $text) { if ($value == $selectedOption) { echo '<option value="' . $value . '" selected="selected">' . $text . '</option>'; } else { echo '<option value="' . $value . '">' . $text . '</option>'; } } } // initialize gender options array $genderOptions = array("0" => "[select]", "1" => "Male", "2" => "Female"); // initialize month options array $monthOptions = array("0" => "[select]", "1" => "January", "2" => "February", "3" => "March", "4" => "April", "5" => "May", "6" => "June", "7" => "July", "8" => "August", "9" => "September", "10" => "October", "11" => "November", "12" => "December"); // initialize some session variables to prevent PHP throwing Notices if (!isset($_SESSION['values'])) { $_SESSION['values']['txtUsername'] = ''; $_SESSION['values']['txtName'] = ''; $_SESSION['values']['selGender'] = ''; $_SESSION['values']['selBthMonth'] = ''; $_SESSION['values']['txtBthDay'] = ''; $_SESSION['values']['txtBthYear'] = ''; $_SESSION['values']['txtEmail'] = ''; $_SESSION['values']['txtPhone'] = ''; $_SESSION['values']['chkReadTerms'] = ''; } if (!isset($_SESSION['errors'])) { $_SESSION['errors']['txtUsername'] = 'hidden'; $_SESSION['errors']['txtName'] = 'hidden'; $_SESSION['errors']['selGender'] = 'hidden'; $_SESSION['errors']['selBthMonth'] = 'hidden'; $_SESSION['errors']['txtBthDay'] = 'hidden'; $_SESSION['errors']['txtBthYear'] = 'hidden'; $_SESSION['errors']['txtEmail'] = 'hidden'; $_SESSION['errors']['txtPhone'] = 'hidden'; $_SESSION['errors']['chkReadTerms'] = 'hidden'; } ?> could you please help me? Quote Link to comment https://forums.phpfreaks.com/topic/129661-fatal-error-cannot-access-private-property-validatemmysqli-on-line-26/ Share on other sites More sharing options...
DarkWater Posted October 22, 2008 Share Posted October 22, 2008 You have Validate::$mMysqli as a private property; it needs to be public in order to be accessed from outside. Why do you have a MySQLi object inside a Validation class though? And no offense, but that's a really sloppy class. Quote Link to comment https://forums.phpfreaks.com/topic/129661-fatal-error-cannot-access-private-property-validatemmysqli-on-line-26/#findComment-672283 Share on other sites More sharing options...
abs0lut Posted October 23, 2008 Author Share Posted October 23, 2008 it should be what? I'm newbie in OOP. Quote Link to comment https://forums.phpfreaks.com/topic/129661-fatal-error-cannot-access-private-property-validatemmysqli-on-line-26/#findComment-672424 Share on other sites More sharing options...
kenshintomoe225 Posted October 25, 2008 Share Posted October 25, 2008 within the realm of OOP, there is such a thing as private or public variable scope (and protected in some cases too) Private means the variable is only available to functions in the exact same class as the private variable. Setting a variable to public makes it available to functions inside the class, as well as other areas of your application that might call on it. For example, if I have a class Foo with private variable $bar $foo = new Foo(); echo $foo.bar; //this is invalid if done by an object that is not of type Foo However, if we set the variable $bar to public in class Foo, we can then access in the fashion outlined above. This is generally not good practice though, to make variables in a class available to all classes, but is ok in some situations. You should use getter and setter methods. For example, lets go back to our class Foo. The new class should look like this: class Foo{ private $bar; function __contruct() { $bar = 0; } function getBar() { return $bar; } function setBar($newBar) { $this->bar = $newBar; } }//end class hope this helps Quote Link to comment https://forums.phpfreaks.com/topic/129661-fatal-error-cannot-access-private-property-validatemmysqli-on-line-26/#findComment-674649 Share on other sites More sharing options...
DarkWater Posted October 25, 2008 Share Posted October 25, 2008 By the way, kenshintomoe, PHP uses the arrow notation (->) to access members of an object, not . like C++ objects and C structs. $foo->bar; is what you wanted. Quote Link to comment https://forums.phpfreaks.com/topic/129661-fatal-error-cannot-access-private-property-validatemmysqli-on-line-26/#findComment-674651 Share on other sites More sharing options...
kenshintomoe225 Posted October 25, 2008 Share Posted October 25, 2008 Thanks for catching that honest mistake on my part, just got done dealing with some java Quote Link to comment https://forums.phpfreaks.com/topic/129661-fatal-error-cannot-access-private-property-validatemmysqli-on-line-26/#findComment-674674 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.