Access an instance variable in constructor - php

I have a class that I call via:
$tagIt_Instance1 = new TagIt;
$tagIt_Instance1->tag_table = 'tags';
// if maintenace is set to true, fill out these (for update)
$tagIt_Instance1->tag_object_table = 'projects'; // the name of your table
$tagIt_Instance1->tag_object_fieldname = 'project_tags'; // the name of your field
$tagIt_Instance1->tag_object_id = isset($_GET['id']) ? $_GET['id'] : ''; // the corresponding id for the row of the table
// end maintenance
if (isset($_GET['tag_it']) && $_GET['tag_it'] == true) {
$tagIt_Instance1->TagItAjax(
isset($_GET['action']) ? $_GET['action'] : '',
isset($_GET['term']) ? $_GET['term'] : '',
isset($_GET['match_id']) ? $_GET['match_id'] : '',
isset($_GET['tag_object_id']) ? $_GET['tag_object_id'] : ''
);
}
In the class, in the constructor, I want to access $tag_table
class TagIt
{
// edit defaults
private $debug = true;
/* this will reload the page if a new tag cannot be added. suggested to leave true as otherwise the user
could submit a page with a tag that is not in the system because of said error. if maintenance is enabled
then the tag would be removed eventually when matching occurs, but lets keep the db clean */
private $reloadOnError = true;
private $confirmationMsgAdd = 'Do you want to add the new tag'; // no question mark or tag identifier, thats handled by jquery
private $confirmationMsgDel = 'Do you want to delete the tag';
private $confirmationMsgDel2 = 'from the database as well';
private $errorNewTag = 'An error occured. Could not process new tag!';
private $generalErrorMsg = 'An error occured.';
// do allow users to delete special cases
private $special_cases = array('featured');
private $select2JS = '<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/select2/3.5.0/select2.min.js"></script>';
private $select2CSS = '<link rel="stylesheet" href="/neou_cms/plugins/select2.css" type="text/css" media="all">';
public $tag_table = '';
/* enabling this will make sure that only tags in the database are
kept for a specific row when tagit checks for matches */
public $maintenance = true;
// do not edit!!! ///////////////////////
// if maintenace is set to true these become applicable (leave blank here)
public $tag_object_table = '';
public $tag_object_fieldname = '';
public $tag_object_id = '';
private $location = '';
public function __construct()
{
// we don't want the query string messing up the AJAX request, thus we remove it
$this->location = strtok($_SERVER["REQUEST_URI"], '?');
echo $this->tag_table;
}
However, whenever I try and access $this->tag_table, I always get an empty variable, despite $this->tag_table working in later functions of the script. I feel like it may be a scope issue, I am not sure.

Your $this->tag_table is empty in the constructor because it's still referencing the unset/empty variable (public $tag_table = '';).
Which is evident with your code:
$tagIt_Instance1 = new TagIt;
$tagIt_Instance1->tag_table = 'tags';
In the above example you're constructing the object and then you only set $tag_table.
You could modify your __construct() to have the tag table passed to it if you require:
function __construct($tag_table) {
// we don't want the query string messing up the AJAX request, thus we remove it
$this->location = strtok($_SERVER["REQUEST_URI"], '?');
// set the tag table, allowing you to access
$this->tag_table = $tag_table;
echo $this->tag_table;
}
Meaning you can skip one step:
$tagIt_Instance1 = new TagIt('tags');
It's in fact, common practice to pass "defining" variables like this through the __construct() method while instantiating a class.

Related

Why does my class constructor feels bloat and faulty?

I'm fairly new to OOP and I'm struggling with setting up my classes. I'm working on a project where I have the following classes: dogTag, dog, user.
This is my current dogTagclass:
class DogTag
{
const POST_TYPE = 'dog-tag';
private ?int $id = null;
private string $number;
private ?Dog $dog;
private ?User $user;
private bool $isActive = false;
private bool $isLost = false;
private string $generationDate;
private ?string $activationDate;
private string $productionStatus;
public function __construct($id = null, string $number, ?Dog $dog = null, ?User $user = null, bool $isActive, bool $isLost, string $generationDate, ?string $activationDate, string $productionStatus)
{
$this->id = $id;
$this->number = $number;
$this->dog = $dog;
$this->user = $user;
$this->isActive = $isActive;
$this->isLost = $isLost;
$this->generationDate = $generationDate;
$this->activationDate = $activationDate;
$this->productionStatus = $productionStatus;
}
Let me explain the functionality of the dog tag. Dog Tags are being generated by a generator and stored into the database. So a dog tag only needs the following arguments when being generated: number (this is a unique generated number and not a unique database ID), isActive, isLost (could be optional), generationDate, productionStatus. All other arguments are not necessarily needed for the generation.
So my first question is: "Do I need to set the optional arguments in the contructor?".
Let me explain why I did this for the moment. When a user receives the unique dog tag number they can activate the dog tag. Therefor I use a method called activateDogTag. For a dog tag to be activated it needs to be attached to a user. Therefor I use the $user argument in the constructor.
Here comes my second question: "Should I use a method setUser(User $user) where I inject the user object into the dogtag class?".
Another problem that I'm struggling with is that I also use an id argument. This will be a bit harder to explain why I'm using this and why it feels wrong.
I'm also using the dogTag class to I can instantiate it with all the data from the database. For the moment I have a static DogTag::get($id) method. This class grabs the data from the database by the ID an instantiates a new DogTag class where I fill all the arguments with the data received from the database.
For information: I'm using WordPress)
public static function get($postId): ?DogTag
{
$post = get_post($postId);
if (empty($post)) {
return null;
}
$dogTagId = $post->ID;
$generationDate = $post->post_date;
$dogTagNumber = get_post_meta($post->ID, 'dog_tag_number', true);
$dogId = get_post_meta($post->ID, 'dog_id', true);
if (empty($dogId)) {
$dog = null;
} else {
$dog = Dog::get($dogId);
}
$userId = $post->post_author;
$user = $userId ? User::get($userId) : null;
$isActive = get_post_meta($dogTagId, 'dog_tag_is_active', true);
$isLost = get_post_meta($dogTagId, 'dog_tag_is_lost', true);
$activationDate = get_post_meta($dogTagId, 'dog_tag_activation_date', true);
$productionStatus = get_post_meta($dogTagId, 'dog_tag_production_status', true);
$dogTag = new self($dogTagId, $dogTagNumber, $dog, $user, $isActive, $isLost,
$generationDate, $activationDate, $productionStatus);
$dogTag->post = get_post($postId);
return $dogTag;
}
This way all the arguments are filled and are available within the class.
So where am I going wrong and what I'm I doing correct? The problem is that I can't really find any solution in my online courses for these problems as they don't go this deep.
Where I'm also struggling is eg with the static activation class (DogTag::activateDogTag):
public static function activateDogTag()
{
// Here goes the form
$dogTag = self::getDogTagByDogTagNumber('4OV9NHOPXLAB6X9B');
// $dogTag = self::getDogTagByDogTagNumber('VBD6JZODTZ6L4YU7');
if (!$dogTag) {
var_dump('no dog tag with this ID found');
}
if(true == $dogTag->getIsActive()) {
var_dump('Dog Tag is already active');
}
if ($dogTag->getUser()) {
var_dump('user is set');
return;
}
var_dump('Activate');
$userId = get_current_user_id();
if (0 === $userId) {
var_dump('not logged in as a user');
}
$dogTag->setIsActive(true);
$dogTag->setUser($userId);
$user = $dogTag->getUser();
var_dump($dogTag);
// Update dog Tag
$args = [
'post_type' => 'dog-tag',
'post_status' => 'publish',
'post_title' => $dogTag->getNumber(),
'post_date' => $dogTag->generationDate,
'post_author' => $dogTag->getUser()->getId(),
'meta_input' => [
'dog_tag_number' => $dogTag->getNumber(),
'dog_tag_is_active' => $dogTag->getIsActive(),
'dog_tag_is_lost' => $dogTag->getIsLost(),
'dog_tag_production_status' => $dogTag->getProductionStatus(),
]
];
var_dump($args);
$postId = wp_update_post($args);
$dogTag->setId($postId);
return $dogTag;
}
Is this a good practice:
$dogTag->setIsActive(true);
$dogTag->setUser($userId);
$user = $dogTag->getUser();
and after the data is stored into the database via wp_update_post by setting the id property via DogTag->setId($postId)?
First of all, if it works then you are not doing anything wrong.
Question 1
It's usually better practice to start with required parameters, followed by optional parameters, if it feels too bloated you could remove all optional parameters from the constructor and create setters for those.
ID/Fetching
What you have here is fine, you could create another class DogTagFactory/DogTagRepository which handles the creation/database process for you if you and reduce bloat.
Overall try not to get too stuck in the chase of "perfect" best practice, it's always going to depend on the situation and usually in the end it does not even matter all that much.

How to avoid the repeating of a path in a URL in php?

I have an URL path like
http://localhost:8080/laravel/api/data/create/
Where /laravel/api is the path from the config file
and /data/create/ is the path which I used in traits.
The problem is everytime when I run the function named connection()repeatedly,
In Tinker, If I do
$data = new Sample;
$data->connection();
http://localhost:8080/laravel/api/data/create/
$data->connection();
http://localhost:8080/laravel/api/data/create/data/create/
$data->connection();
http://localhost:8080/laravel/api/data/create/data/create/data/create/
The path /data/create/ is repeated every time when I perform connection().
It should not be like that, only once the path should be appended, if we perform connection(), like the below.
$data->connection();
http://localhost:8080/laravel/api/data/create/
I am using a method chaining for appending path .
protected $resource[]; //is declared already in the code
protected $url[];
public function addPath()
{
$old_uri = explode('/', $this->resource['path']);
$add_uri = explode('/', $this->path);
$new_uri = array_merge($old_uri, $add_uri);
$this->resource['path'] = '/'.implode('/', array_filter($new_uri));
return $this;
}
public function connection()
{
$this->addPath()->unparse_url();
return $url;
}
private function unparse_url()
{
$scheme = isset($this->resource['scheme']) ? $this->resource['scheme'].'://' : '';
$host = isset($this->resource['host']) ? $this->resource['host'] : '';
$port = isset($this->resource['port']) ? ':'.$this->resource['port'] : '';
$user = isset($this->resource['user']) ? $this->resource['user'] : '';
$pass = isset($this->resource['pass']) ? ':'.$this->resource['pass'] : '';
$pass = ($user || $pass) ? "$pass#" : '';
$path = isset($this->resource['path']) ? $this->resource['path'] : '';
$query = isset($this->resource['query']) ? '?'.$this->resource['query'] : '';
$fragment = isset($this->resource['fragment']) ? '#'.$this->resource['fragment'] : '';
$this->url = "$scheme$user$pass$host$port$path$query$fragment";
return $this;
}
Could someone please help to fix the issue?
Thanks.
If we disregard from your undefined variables, the issue is that your code appends the path every time you call the connection()-method since it calls the addPath()-method.
If you only want it to append it once, there are some alternatives.
Alternative 1
If you always want the path to be added, you can simple call the addPath()-method from the constructor instead.
public function __construct()
{
$this->addPath()->unparse_url();
}
and just have the connection()-method like this:
public function connection()
{
return $this->url;
}
This would work well as long as you don't need to use the original values of $this->url and $this->resource['path'] for anything since they will be changed when the class is instantiated.
Alternative 2
You can set class property as a flag, saying if the path already been added or not. Then you simply check that flag in your addPath()-method.
// Default value is false, since we haven't added it yet
protected $pathAdded = false;
public function addPath()
{
if ($this->pathAdded === false) {
// It's still false so it hasn't been added yet
$old_uri = explode('/', $this->resource['path']);
$add_uri = explode('/', $this->path);
$new_uri = array_merge($old_uri, $add_uri);
$this->resource['path'] = '/'.implode('/', array_filter($new_uri));
// Set the flag to true so we know it's already been done
$this->pathAdded = true;
}
return $this;
}
This way, it will only append the path on the first call to that method.

PHP class not setting one of my variables

I have a class that I use to display pages, and I set many class wide variables in the constructor. One of them is coming up null, even though I can see in the call to create the object that the argument is passed. Here is the constructor for the class:
public function __contruct(string $pageTitle, string $page, bool $csrfFlag, string $pageType) {
$this->pageTitle = $pageTitle;
$this->page = $page;
$this->csrfFlag = $csrfFlag;
// Validating page type passed
switch ($pageType) {
case "main":
case "profile":
case "admin":
$this->pageType = $pageType;
default:
throw new Exception("A page type variable was passed that is unknown. That variable was $pageType");
}
}
And here is the particular object creation call:
$display = new PageDisplay('Login', 'login.php', true, 'auth_page');
The problem I'm having is that the variable marked $page isn't being passed through (and I know that because I try and call a late function in the class that displays pages and when it comes to the line about displaying the actual page (in this case, login.php) it gives me this error:Failed opening '' for inclusion). Here is that function if you would like to see it:
// Ultimately builds the page to show the user
public function buildPage(bool $needsHeadTags) : void {
// Generate CSRF token if needed
if ($this->csrfFlag === true) { $csrfToken = hash("sha512", random_bytes(64)); }
// Get extra HTML
if ($needsHeadTags === true) { $extraHeadTags = $this->getHeadTags(); }
$headerHtml = $this->getHeader();
$pageTitle = $this->pageTitle;
// Show page
include_once $this->page; // where the error is thrown
}
But I can see that it is passed in the constructor. What am I doing wrong?
<?php
declare(strict_types=1);
class PageDisplay {
private $simplePageNav = true;
private $header = "";
private $pageTitle;
private $page;
private $csrfFlag;
private $pageType;
// Sets the variables the rest of the class will use
public function __contruct(string $pageTitle, string $page, bool $csrfFlag, string $pageType) {
$this->pageTitle = $pageTitle;
$this->page = $page;
$this->csrfFlag = $csrfFlag;
// Validating page type passed
switch ($pageType) {
case "main":
case "profile":
case "admin":
$this->pageType = $pageType;
default:
throw new Exception("A page type variable was passed that is unknown. That variable was $pageType");
}
}
public function getPage() : string {
return $this->page;
}
// If the function returns true, it is just a simple navigation to the page
public static function isPageNav(bool $getAllowed) : bool {
// Checking if GET parameters are allowed, then checking if the correct things are empty, then return boolean with what we find
if (!$getAllowed) {
$simplePageNav = (empty($_POST) && empty($_GET) && empty(file_get_contents("php://input"))) ? true : false;
} else {
$simplePageNav = (empty($_POST) && empty(file_get_contents("php://input"))) ? true : false;
}
return $simplePageNav;
}
// Gets what the navigation should be based on what type of page the user went to (general web, profile, admin, etc...)
private function getHeader() : string {
// Control statement to display website correctly
switch($this->pageType) {
case "auth_page":
return "";
break;
}
return "hard";
}
// Gets what the additional head tags should be based on what type of page the user went to (general web, profile, admin, etc...)
private function getHeadTags() : string {
// Control statement to display website correctly
switch($this->pageType) {
//
}
}
// Ultimately builds the page to show the user
public function buildPage(bool $needsHeadTags) : void {
// Generate CSRF token if needed
if ($this->csrfFlag === true) { $csrfToken = hash("sha512", random_bytes(64)); }
// Get extra HTML
if ($needsHeadTags === true) { $extraHeadTags = $this->getHeadTags(); }
$headerHtml = $this->getHeader();
$pageTitle = $this->pageTitle;
// Show page
include_once $this->page;
}
}
PHP has a number of "special" methods that can be added to classes that get automatically called at points during the class lifecycle. The __construct function is executed on object initialisation, and __destruct on object destruction, when there are no remaining references to the object or when the script or program ends. It's totally legal to create other class functions that also start with a double underscore, so PHP will not complain about this:
class PageDisplay {
// Sets the variables the rest of the class will use
public function __contruct(string $pageTitle, string $page, bool $csrfFlag, string $pageType) {
// code not executed unless $object->__contruct is called
}
}
but the code in the __contruct function will not be executed when a new PageDisplay object is created.
The fix is simple:
class PageDisplay {
// Sets the variables the rest of the class will use
public function __construct(string $pageTitle, string $page, bool $csrfFlag, string $pageType) {
// code executed on calling new PageDisplay('...')
}
}

Creating default object from empty value (adding an item to a database for a new user in Laravel)

I have a function I am using to add
I have an array $data that contains the user data I am trying to put into the db. Everything works except for the "makeUrlTag" function portion:
public function makeUrlTag() {
$url_tag = '';
if(isset($this->data['user']['first_name'])) {
$url_tag = $url_tag . $this->data['user']['first_name'];
}
if(isset($this->data['user']['last_name'])) {
$url_tag = $url_tag.$this->data['user']['last_name'];
}
$fan->url_tag = $url_tag;
}
public function createFan() {
$fan = new Fan;
$fan->fbid = isset($this->data['user']['id']) ? $this->data['user']['id'] : '';
$fan->email = isset($this->data['user']['email']) ? $this->data['user']['email'] : '';
$fan->first_name = isset($this->data['user']['first_name']) ? $this->data['user']['first_name'] : '';
$fan->last_name = isset($this->data['user']['last_name']) ? $this->data['user']['last_name'] : '';
$this->makeUrlTag();
$fan->save();
}
I call createFan with:
$this->createFan();
When I run this, I get the error:
Creating default object from empty value
in reference to the makeUrlTag(); portion. Particularly the line:
$fan->url_tag = $url_tag;
Any idea what's going on here? Again, taking out the makeUrlTag portion works fine. Thank you.
It's because your makeUrlTag() method doesn't know about the Fan which is in the $fan variable you created in the createFan() method and trying to use a non-existing object in the scope of makeUrlTag() method using this:
$fan->url_tag = $url_tag;
So, you need to make your $fan object available to makeUrlTag() and to do this you may add a protected property in your class:
class YourClass {
protected $fan = null;
public function makeUrlTag(){
$url_tag = '';
// ...
$this->fan->url_tag = $url_tag;
}
public function makeUrlTag(){
$this->fan = new Fan;
// rest of your code
// but use $this->fan instead of $fan
$this->fan->save();
}
}
So, now you can access the $fan object from any method of your class ussing $this->fan, that's it.

An example of an MVC controller

I have been reading a lot about how and why to use an MVC approach in an application. I have seen and understand examples of a Model, I have seen and understand examples of the View.... but I am STILL kind of fuzzy on the controller. I would really love to see a thorough enough example of a controller(s). (in PHP if possible, but any language will help)
Thank you.
PS: It would also be great if I could see an example of an index.php page, which decides which controller to use and how.
EDIT: I know what the job of the controller is, I just don't really understand how to accomplish this in OOP.
Request example
Put something like this in your index.php:
<?php
// Holds data like $baseUrl etc.
include 'config.php';
$requestUrl = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$requestString = substr($requestUrl, strlen($baseUrl));
$urlParams = explode('/', $requestString);
// TODO: Consider security (see comments)
$controllerName = ucfirst(array_shift($urlParams)).'Controller';
$actionName = strtolower(array_shift($urlParams)).'Action';
// Here you should probably gather the rest as params
// Call the action
$controller = new $controllerName;
$controller->$actionName();
Really basic, but you get the idea... (I also didn't take care of loading the controller class, but I guess that can be done either via autoloading or you know how to do it.)
Simple controller example (controllers/login.php):
<?php
class LoginController
{
function loginAction()
{
$username = $this->request->get('username');
$password = $this->request->get('password');
$this->loadModel('users');
if ($this->users->validate($username, $password))
{
$userData = $this->users->fetch($username);
AuthStorage::save($username, $userData);
$this->redirect('secret_area');
}
else
{
$this->view->message = 'Invalid login';
$this->view->render('error');
}
}
function logoutAction()
{
if (AuthStorage::logged())
{
AuthStorage::remove();
$this->redirect('index');
}
else
{
$this->view->message = 'You are not logged in.';
$this->view->render('error');
}
}
}
As you see, the controller takes care of the "flow" of the application - the so-called application logic. It does not take care about data storage and presentation. It rather gathers all the necessary data (depending on the current request) and assigns it to the view...
Note that this would not work with any framework I know, but I'm sure you know what the functions are supposed to do.
Imagine three screens in a UI, a screen where a user enters some search criteria, a screen where a list of summaries of matching records is displayed and a screen where, once a record is selected it is displayed for editing. There will be some logic relating to the initial search on the lines of
if search criteria are matched by no records
redisplay criteria screen, with message saying "none found"
else if search criteria are matched by exactly one record
display edit screen with chosen record
else (we have lots of records)
display list screen with matching records
Where should that logic go? Not in the view or model surely? Hence this is the job of the controller. The controller would also be responsible for taking the criteria and invoking the Model method for the search.
<?php
class App {
protected static $router;
public static function getRouter() {
return self::$router;
}
public static function run($uri) {
self::$router = new Router($uri);
//get controller class
$controller_class = ucfirst(self::$router->getController()) . 'Controller';
//get method
$controller_method = strtolower((self::$router->getMethodPrefix() != "" ? self::$router->getMethodPrefix() . '_' : '') . self::$router->getAction());
if(method_exists($controller_class, $controller_method)){
$controller_obj = new $controller_class();
$view_path = $controller_obj->$controller_method();
$view_obj = new View($controller_obj->getData(), $view_path);
$content = $view_obj->render();
}else{
throw new Exception("Called method does not exists!");
}
//layout
$route_path = self::getRouter()->getRoute();
$layout = ROOT . '/views/layout/' . $route_path . '.phtml';
$layout_view_obj = new View(compact('content'), $layout);
echo $layout_view_obj->render();
}
public static function redirect($uri){
print("<script>window.location.href='{$uri}'</script>");
exit();
}
}
<?php
class Router {
protected $uri;
protected $controller;
protected $action;
protected $params;
protected $route;
protected $method_prefix;
/**
*
* #return mixed
*/
function getUri() {
return $this->uri;
}
/**
*
* #return mixed
*/
function getController() {
return $this->controller;
}
/**
*
* #return mixed
*/
function getAction() {
return $this->action;
}
/**
*
* #return mixed
*/
function getParams() {
return $this->params;
}
function getRoute() {
return $this->route;
}
function getMethodPrefix() {
return $this->method_prefix;
}
public function __construct($uri) {
$this->uri = urldecode(trim($uri, "/"));
//defaults
$routes = Config::get("routes");
$this->route = Config::get("default_route");
$this->controller = Config::get("default_controller");
$this->action = Config::get("default_action");
$this->method_prefix= isset($routes[$this->route]) ? $routes[$this->route] : '';
//get uri params
$uri_parts = explode("?", $this->uri);
$path = $uri_parts[0];
$path_parts = explode("/", $path);
if(count($path_parts)){
//get route
if(in_array(strtolower(current($path_parts)), array_keys($routes))){
$this->route = strtolower(current($path_parts));
$this->method_prefix = isset($routes[$this->route]) ? $routes[$this->route] : '';
array_shift($path_parts);
}
//get controller
if(current($path_parts)){
$this->controller = strtolower(current($path_parts));
array_shift($path_parts);
}
//get action
if(current($path_parts)){
$this->action = strtolower(current($path_parts));
array_shift($path_parts);
}
//reset is for parameters
//$this->params = $path_parts;
//processing params from url to array
$aParams = array();
if(current($path_parts)){
for($i=0; $i<count($path_parts); $i++){
$aParams[$path_parts[$i]] = isset($path_parts[$i+1]) ? $path_parts[$i+1] : null;
$i++;
}
}
$this->params = (object)$aParams;
}
}
}
Create folder structure
Setup .htaccess & virtual hosts
Create config class to build config array
Controller
Create router class with protected non static, with getters
Create init.php with config include & autoload and include paths (lib, controlelrs,models)
Create config file with routes, default values (route, controllers, action)
Set values in router - defaults
Set uri paths, explode the uri and set route, controller, action, params ,process params.
Create app class to run the application by passing uri - (protected router obj, run func)
Create controller parent class to inherit all other controllers (protected data, model, params - non static)
set data, params in constructor.
Create controller and extend with above parent class and add default method.
Call the controller class and method in run function. method has to be with prefix.
Call the method if exisist
Views
Create a parent view class to generate views. (data, path) with default path, set controller, , render funcs to
return the full tempalte path (non static)
Create render function with ob_start(), ob_get_clean to return and send the content to browser.
Change app class to parse the data to view class. if path is returned, pass to view class too.
Layouts..layout is depend on router. re parse the layout html to view and render
Please check this:
<?php
global $conn;
require_once("../config/database.php");
require_once("../config/model.php");
$conn= new Db;
$event = isset($_GET['event']) ? $_GET['event'] : '';
if ($event == 'save') {
if($conn->insert("employee", $_POST)){
$data = array(
'success' => true,
'message' => 'Saving Successful!',
);
}
echo json_encode($data);
}
if ($event == 'update') {
if($conn->update("employee", $_POST, "id=" . $_POST['id'])){
$data = array(
'success' => true,
'message' => 'Update Successful!',
);
}
echo json_encode($data);
}
if ($event == 'delete') {
if($conn->delete("employee", "id=" . $_POST['id'])){
$data = array(
'success' => true,
'message' => 'Delete Successful!',
);
}
echo json_encode($data);
}
if ($event == 'edit') {
$data = $conn->get("select * from employee where id={$_POST['id']};")[0];
echo json_encode($data);
}
?>

Categories