I need a little help understanding how to use OOP in PHP to perform a form submission action. The task is at hand ... I'm trying to learn how to write PHP code using OOP. So far, I understand the general idea of ββclasses, functions, calling functions, inheritance, etc.
I created a simple project for practice that allows the user to search for food in a specific place. So far I have a form with 2 <input>
fields. Normally for a form action I would do <form action="actionFileName.php">
, but now that I have a class with a function to handle the form, what do I use for the action value?
I was thinking of creating an instance of the class and calling a function that processes the form, but I get the object was not found! after I submit the form with echo
values ββfrom the else
in hungryClass.php
displayed in the address bar.
how can i fix this? Thanks.
What my code looks like: HTML form
<?php require_once 'hungryClass.php'; $newSearch = new hungryClass(); ?> <form action="<?php $newSearch->searchMeal();?>" method="post" id="searchMealForm"> <input type="search" size="35" placeholder="What Food Are you looking for?" id="mealName" class="meal"/> <input type="search" placeholder="City Area" id="mealLocation" class="meal"> <input type="submit" value="Satisfy Me" id="findMeal" /> </form>
Page in processing form (hungryClass.php)
<?php require_once('dbConnect.php'); class hungryClass{ public function searchMeal(){ //call connection function. $connect = new dbConnect(); //validate input if(isset($_POST['mealName'])){ $meal = $_POST['mealName']; //ensure value is a string. $cleanse_meal = filter_var($meal, FILTER_SANITIZE_STRING); echo $cleanse_meal; } else{ echo "Please supply the meal you crave"; } //validate location if(isset($_POST['mealLocation'])){ $location = $_POST['mealLocation']; //validate and sanitize input. ensure value is a string. $cleanse_location = filter_var($location, FILTER_SANITIZE_STRING); echo $cleanse_location; } else{ echo "Please supply a location"; }
}
Database class
<?php class dbConnect{ private $host = "localhost"; private $user = "stacey"; private $pass = ""; private $db_name = "menu_finder"; private $connect; //private static $dbInstance; public function __construct(){ try{ $this->connect = new mysqli($host, $user, $pass, $db_name); if(mysqli_connect_error()){ die('connection error('.mysqli_connect_errno().')' . mysqli_connect_error()); } } catch(Exception $e){ echo $e->getMessage(); } }
? >
source share