我需要一点帮助来了解如何在 PHP 中使用 OOP 来执行表单提交操作。手头的任务...我正在尝试学习如何使用 OOP 编写 PHP 代码。到目前为止,我了解类、函数、调用函数、继承等的一般概念。
我创建了一个简单的练习项目,允许用户在某个位置搜索餐点。到目前为止,我有一个包含 2 个<input>
字段的表单。通常对于表单操作,我会这样做,<form action="actionFileName.php">
但现在我有一个具有处理表单功能的类,我将什么用于操作值?
我想创建一个类的实例并调用处理表单的函数,但我得到一个找不到对象!在我提交表单后的页面,其中包含在地址栏中显示的语句中的echo
值。else
hungryClass.php
我该如何解决?谢谢。
我的代码是什么样的:HTML 表单
<?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>
处理表单的页面 (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";
}
}
数据库类
<?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();
}
}
?>