PHP - Php Class Tutorial
I followed the tutorial at http://www.devshed.com/c/a/PHP/Building-An-Extensible-Form-Validator-Class/ because I wanted to have an easier way to build and maintain form validation.
I completed the tutorial, but the form does not register the form as being filled out. Here is the class code (FormValidator.class.inc) <?php //FormValidator.class.inc //class to perform form validation class FormValidator { //---------------private variables------------------ var $_errorList; //the _ prefix is used to distinguish private variables from public variables //---------------methods (private)------------------ //functio to get the value of a variable (field) function _getValue($field) { global ${$field}; //makes the field entry a global variable return ${$field}; } //---------------methods (public)------------------- //it is a good idea to run resetErrorList() whenever the class is first initialized //PHP makes it possible to automatically execute a specific function when a new instance of a class is spawned. This function is referred to as a "constructor" and must have the same name as the class. //reset error list function FormValidator() { $this->resetErrorList(); } //begin basic validation routines //check whether input is empty //the isEmpty public method is called with 2 arguments, one for the form variable and one for the error message //the method internally calls the _getValue method and then trim()s the result to check if it is empty // if the variable is empty, a new element is added class variable $_errorList (an array) to represent the error. This new element is itself a three-element associative array, with the keys "field", "value" and "msg", representing the form variable name, the current value of that variable, and the corresponding error message // if the variable is not empty, it will pass the test and return true // this function, along with _getValue, allows the user to get both the field name and the field value //the $this prefix provides a convenient way to access variables and functions which are "local" to the class. function isEmpty($field, $msg) { $value = $this->_getValue($field); if (trim($value) == "") { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } //check whether input is a string function isString($field, $msg) { $value = $this->_getValue($field); if(!is_string($value)) { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } //check whether input is a number function isNumber($field, $msg) { $value = $this->_getValue($field); if(!is_numeric($value)) { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } //check whether input is an integer function isInteger($field, $msg) { $value = $this->_getValue($field); if(!is_integer($value)) { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } //check whether input is a float function isFloat($field, $msg) { $value = $this->_getValue($field); if(!is_float($value)) { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } //check whether input is within a valid numeric range function isWithinRange($field, $msg, $min, $max) { $value = $this->_getValue($field); if(!is_numeric($value) || $value < $min || $value > $max) { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } //check whether the input is alphanumeric function isAlpha($field, $msg) { $value = $this->_getValue($field); $pattern = "/^[a-zA-Z]+$/"; if (preg_match($pattern, $value)) { return true; } else { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } } //check whether input is a valid email address function isEmailAddress($field, $msg) { $value = $this->_getValue($field); $pattern = "/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/ "; if (preg_match($pattern, $value)) { return true; } else { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } } //end basic validation routines----- //return the list of current errors function getErrorList() { return $this->_errorList; } //check whether any errors have occured in validation //this method checks the size of the $_errorList array; if the size is greater than one, it implies that one or more errors have occured during validation //it returns a Boolean value function isError() { if(sizeof($this->_errorList) > 0) { return true; } else { return false; } } //reset the error list to a blank array function resetErrorList() { $this->_errorList = array(); } }//end FormValidator class ?> -------Here is the form (simpleform.html) <html> <head> <basefont face="Arial"> </head> <body> <form action="processor.php" method="POST"> <b>Name:</b> <br> <input type="text" name="name" size="15"> <p> <b>Age:</b> <br> <input type="text" name="age" size="2" maxlength="2"> <p> <b>Sex:</b> <br> <input type="Radio" name="sex" value="m">Male <input type="Radio" name="sex" value="f">Female <p> <b>Favourite sandwich type:</b> <br> <select name="stype"> <option value="">-select one-</option> <option value="1">Thin crust</option> <option value="2">Thick crust</option> <option value="3">Toasted</option> </select> <p> <b>Favourite sandwich filling:</b> <br> <input type="Checkbox" name="sfill[]" value="BLT">Bacon, lettuce tomato <input type="Checkbox" name="sfill[]" value="EC">Egg and cheese <input type="Checkbox" name="sfill[]" value="PBJ">Peanut butter and jelly <p> <input type="Submit" name="submit" value="Save"> </form> </body> </html> ------and here is processor.php <?php //include class include("FormValidator.class.inc"); // instantiate object $fv = new FormValidator(); //perform validation $fv->isEmpty("name", "Please enter a name"); $fv->isNumber("age", "Please enter a valid age"); $fv->isWithinRange("age", "Please enter an age within the numeric range 1-99", 1, 99); $fv->isEmpty("sex", "Please enter your sex"); $fv->isEmpty("stype", "Please select one of the listed sandwich types"); $fv->isEmpty("sfill", "Please select one or more of the listed sandwich fillings"); if($fv->isError()) { $errors = $fv->getErrorList(); echo "<b>The operation could not be performed because one or more error(s) occurred.</b> <p> Please resubmit the form after making the following changes:"; echo "<ul>"; foreach($errors as $e) { echo "<li>" . $e['msg'] . "</li>"; } echo "</ul>"; } else { //do something useful with the data echo "Data OK"; } ?> Similar TutorialsI have mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me Ok. I know you can pass the object of a class as an argument. Example: class A { function test() { echo "This is TEST from class A"; } } class B { function __construct( $obj ) { $this->a = $obj; } function test() { $this->a->test(); } } Then you could do: $a = new A(); $b = new B($a); Ok so that's one way i know of. I also thought that you could make a method static, and do this: (assuming class A's test is 'static') class B { function test() { A::test(); } } But that is not working. I'd like to know all possible ways of accomplishing this. Any hints are appreciated. thanks Hi Can you call Class A's methods or properties from Class B's methods? Thanks. I have an existing instance of my class Database, now I want to call that instance in my Session class, how would I go about doing this? If a class has a constructor but also has a static method, if I call the static method does the constructor run so that I can use an output from the constructor in my static method? --Kenoli This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=308352.0 I have a need to create a form that will get info from a mysql table, show that info, two fields one of which I want to be a checkbox that will need to update the table with either a 0 or a 1. I will later use that info. I have searched all over and haven't found what I am looking for. I can find tutorials for creating checkboxes but nothing what I need / want
Hello Php Freaks I am following this tutorial how to make a login for my website, the only trouble is that... It dosen't seem to work, so i wanna know if its only me who cant make it work... and if it is why XD... Tutorial can be found he http://www.knowledgesutra.com/forums/topic/7887-php-simple-login-tutorial/ Now when i get started it starts saying error at line 6: if ($_GET["op"] == "login") It says that when im about to login right above the login. Now when i put in data i get error on line 19: $r = mysql_query($q); That one, and i have no idea how to fix it. Anyone please ? This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=130332.0 Can someone provide me with a good tutorial on how to create really nice looking buttons please. Not just crap ones, like real nice ones. XD Thanks in advance This topic has been moved to Linux. http://www.phpfreaks.com/forums/index.php?topic=334310.0 Hello, I'm making a website which includes an articles page. I want users to be able to search for particular articles. For this search function I used the Simple SQL Search tutorial from phpfreaks (http://www.phpfreaks.com/tutorial/simple-sql-search). It's working quite well but i'd like to expand it a little. The most important thing i want changed is what happens when users enters a string which holds multiple words. The function from the tutorial perceives these words as one string and searches for that string as a whole. For example when a user enters 'winter 2012' and an article holds the string 'winter of 2012', the function returns no matches. This is, ofcourse, not the way i'd like it to function. I've managed to seperate the words and search for them individually by using explode and foreach, but now i'm getting duplicate results when an article holds mulitple words from the users' entry string. My idea to fix this was to make an array with the article id's of the articles that have matched, and then to exclude them from the SQL query for the next word from the search string by using 'NOT IN $array' in the where clause. Unfortunately i haven't managed to succeed with this so far and that's why i ask for your help.. This my search function: Code: [Select] function zoekopdracht() { require('dbcon.php'); $zoekopdr = trim($_GET['zzoek']); $zoekopdr = strip_tags($zoekopdr); if (strlen($zoekopdr) < 3) { echo "De zoekopdr moet minimaal 3 karakters bevatten."; } else { $zoekopdr = explode(" ", $zoekopdr); foreach($zoekopdr as $zoekterm) { $zoekopdrDB = mysql_real_escape_string($zoekterm); $searchSQL = "SELECT * FROM n_artikelen WHERE "; $types = array(); $types[] = isset($_GET['zartikel'])?" volledig_artikel LIKE '%{$zoekopdrDB}%'":''; $types[] = isset($_GET['ztitel'])?" titel LIKE '%{$zoekopdrDB}%'":''; $types[] = isset($_GET['zjaar'])?" YEAR(publicatie) LIKE '%{$zoekopdrDB}%'":''; $types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked) if (count($types) < 1) { $types[] = "volledig_artikel LIKE '%{$zoekopdrDB}%'"; // use the artikel + titel as a default search if none are checked $types[] = "titel LIKE '%{$zoekopdrDB}%'"; } $searchSQL .= implode(" OR ", $types) . " ORDER BY publicatie LIMIT 0,10"; $searchResult = mysql_query($searchSQL) or die(mysql_error()); if (mysql_num_rows($searchResult) < 1) { echo "De zoekopdracht '{$zoekopdr}' heeft geen resultaten."; } else { while ($row = mysql_fetch_array($searchResult, MYSQL_NUM)) { artikelelement($row); // function that outputs the result of $row[] } } } } } Additionally, if this problem is fixed, i'd love to see a way to sort the results on closest match (article which matches two words > article which matches one word). Thanks! This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=330907.0 I am following a tutorial on how to make a simple PHP shopping cart at: http://v3.thewatchmakerproject.com/journal/276/ I have discovered a problem with the code where a } is not closed. Quote $cart = $_SESSION['cart']; if ($cart) { $items = explode(',',$cart); $contents = array(); foreach ($items as $item) { $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1; } Should the } go on the end of the code or is it suppose to go else where within it? This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=351363.0 I found this amazing tutorial and i try to change it for a different database, but when i do a search it never finds anything. <?php $dbHost = 'localhost'; // localhost will be used in most cases // set these to your mysql database username and password. $dbUser = 'root'; $dbPass = '123'; $dbDatabase = 'ergasia2'; // the database you put the table into. $con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error()); mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error()); // Set up our error check and result check array $error = array(); $results = array(); // First check if a form was submitted. // Since this is a search we will use $_GET if (isset($_GET['search'])) { $searchTerms = trim($_GET['search']); $searchTerms = strip_tags($searchTerms); // remove any html/javascript. if (strlen($searchTerms) < 3) { $error[] = "Ο όρος αναζήτησις πρέπει να είναι έχει περισσότερους από 3 χαρακτήρες."; }else { $searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection. } // If there are no errors, lets get the search going. if (count($error) < 1) { $searchSQL = "SELECT Fname, Surname, StreetName, status FROM EMPLOYEES WHERE "; // grab the search types. $types = array(); $types[] = isset($_GET['Fname'])?"`Fname` LIKE '%{$searchTermDB}%'":''; $types[] = isset($_GET['Surname'])?"`Surname` LIKE '%{$searchTermDB}%'":''; $types[] = isset($_GET['StreetName'])?"`StreetName` LIKE '%{$searchTermDB}%'":''; $types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked) if (count($types) < 1) $types[] = "`sbody` LIKE '%{$searchTermDB}%'"; // use the body as a default search if none are checked $andOr = isset($_GET['matchall'])?'AND':'OR'; $searchSQL .= implode(" {$andOr} ", $types) . " ORDER BY `stitle`"; // order by title. $searchResult = mysql_query($searchSQL) or trigger_error("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$searchSQL}"); if (mysql_num_rows($searchResult) < 1) { $error[] = "The search term provided {$searchTerms} yielded no results."; }else { $results = array(); // the result array $i = 1; while ($row = mysql_fetch_assoc($searchResult)) { $results[] = "{$i}: {$row['stitle']}<br />{$row['sdescription']}<br />{$row['sbody']}<br /><br />"; $i++; } } } } function removeEmpty($var) { return (!empty($var)); } ?> <html> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>My Simple Search Form</title> <style type="text/css"> #error { color: red; } </style> <body> <?php echo (count($error) > 0)?"The following had errors:<br /><span id=\"error\">" . implode("<br />", $error) . "</span><br /><br />":""; ?> <form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" name="searchForm"> Search For: <input type="text" name="search" value="<?php echo isset($searchTerms)?htmlspecialchars($searchTerms):''; ?>" /><br /> Search In:<br /> Body: <input type="checkbox" name="body" value="on" <?php echo isset($_GET['body'])?"checked":''; ?> /> | Title: <input type="checkbox" name="title" value="on" <?php echo isset($_GET['title'])?"checked":''; ?> /> | Description: <input type="checkbox" name="desc" value="on" <?php echo isset($_GET['desc'])?"checked":''; ?> /><br /> Match All Selected Fields? <input type="checkbox" name="matchall" value="on" <?php echo isset($_GET['matchall'])?"checked":''; ?><br /><br /> <input type="submit" name="submit" value="Search!" /> </form> <?php echo (count($results) > 0)?"Your search term: {$searchTerms} returned:<br /><br />" . implode("", $results):""; ?> </body> </html> The table which i use is the following ---------------- |EMPLOYEES| ---------------- |ssn | ---------------- |Fname ---------------- |postal code | ---------------- |salary | ---------------- |street name| ---------------- |street number | ------------------- |surname | ----------------- |UnionMembershipNumber| --------------------------------- |password | ----------------- |status | ---------------- This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=343600.0 Hi, I need to be able to call a class based on variables. E.G. I would normally do: Code: [Select] $action = new pattern1() but i would like to be able to do it dynamicaly: Code: [Select] $patNum = 1; $action = new pattern.$patNum.() Im wondering if that's possible? If so what would the correct syntax be? Many Thanks. Hi, I am very new to php and im trying to work out a bit of code... I googled for help but im just stuck at this point... <input type="text" name="rates1" value="<?php echo $rates; ?>"> How can I echo rates1 to reflect whats in a table... Thanks in advance... i have to add a ckeditor to my CMS backend to the description textarea but no idea where or how to start.. anybody knows a good tutorial online i could use?? |