Using CodeIgniter, input information into a textbox and verify if there is a corresponding record in the database when submitting

Working on a CodeIgniter project, I am faced with the task of adding information to a form within my view page called meal_add.php. Below is the form structure:

<div id="content" class="box">
    <form action="<?php echo base_url(); ?>index.php/admin_logins/meal2" method="post">
        <fieldset>
            <legend id="add_employee_legend">
                Add Meal Information
            </legend>
            <div>
                <label id= "emp_id_add_label">Employee ID:</label>
                <input type="text" name="emp_id" id = "employee_id_add" placeholder="Employee ID" required="1"/>
            </div>
            <br>
            <div>
                <label id= "is_guest_add_label">Guests?</label>
                <input type="checkbox" name ="is_guest_checkbox" class ="guestcheck" value="1" onchange="valueChanged()"/>
            </div>
            <br>
            <div id = "guestnum" hidden = "true">
                <label id= "num_of_guest_add_label">No. of Guests:</label>
                <input type="text" name="num_of_guest" id = "num_of_guest_add" placeholder='0'/>
            </div>
            <div>
                <label id= "remarks_add_label">Remarks:</label>
                <textarea rows="1" cols="20" style="margin-left: 35px"></textarea>
            </div>
            <input type="submit" name="submit" id = "meal_info_submit" value="Save Meal Information"/>
            <button id = "cancel_button" onclick="location.href='<?php echo base_url(); ?>index.php/admin_logins/meal'">
                Cancel
            </button>
        </fieldset>
    </form>

The controller method for adding data is as follows -

function meal2()
{
    if($_POST)
    {
        date_default_timezone_set('Asia/Dacca');
        $mdata['emp_id'] = $this->input->post('emp_id');
        $mdata['entry_date'] = date('Y-m-d');
        $mdata['is_guest'] = $this->input->post('is_guest_checkbox');
        $mdata['num_of_guest'] = $this->input->post('num_of_guest');

        $mdata['remarks'] = $this->input->post('remarks');
        $res = $this->meal_model->insert_meal($mdata);
        if($res)
        {   
            $this->session->set_flashdata('message','Meal information added successfully');
            redirect("admin_logins/meal");
        }
    }
    else
    {
        $this->load->view('admin_logins/meal_add');
    }

}

And the model method for insertion is -

public function insert_meal($data)
{
    return $this->db->insert('meal', $data);    
}

In the database, there is a table named employee with fields as shown below:

column         |   data type
--------------|--------------
id               |   int PK
emp_id      |   varchar(15)
emp_name  |   varchar(50)
emp_mobile_no | varchar(15)

Another table named meal has the following structure:

column          |  data type
--------------|-------------
id                 |   int PK
emp_id        |   varchar(15)
entry_date    |    date
is_guest          |    int
num_of_guest  |   int
remarks           |    text

The objective is to match the entered Employee ID in the form on the meal_add.php page with values from employee.emp_id. If a match is found, data should be saved in the meal table using the corresponding employee.id. If no match is found, show a PHP flash message stating that the ID does not exist on the meal_add.php page. While I understand that a JOIN query is necessary, the text matching part is proving challenging. Any guidance on organizing code and where to implement it would be greatly appreciated.

The database used here is MySQL.

EDIT - 1:

Within the controller method, I have attempted the following -

$temp = $this->input->post('emp_id');
$sql = "SELECT e.id FROM employee AS e WHERE e.emp_id = ?";
$mdata['emp_id'] = $this->db->query($sql, $temp)->emp_id;

if($mdata['emp_id'] == '')
{
    $this->session->set_flashdata('message','Employee ID does not exist');
    redirect("admin_logins/meal");
}

But regardless of the input provided in $temp, I always receive the flash message and get redirected. Additionally, I tried this -

echo "<pre>";
print_r($mdata);
die();

After which, upon executing echo and print_r(), I encountered the following output -

A PHP Error was encountered

Severity: Notice

Message: Undefined property: CI_DB_mysql_result::$emp_id

Filename: controllers/admin_logins.php

Line Number: 150

Array
(
    [emp_id] => 
)

Answer №1

It seems like the solution you're looking for is $this->db->insert_id()

For more information, check out the documentation here:

Additionally, consider proper form validation for CodeIgniter.

UPDATE

Apologies for my misunderstanding earlier. Please refer to generating query results.

$q = $this->db->query($sql, $temp);
if ($q->num_rows() > 0) {
    // If there is a match, then the emp_id is valid
    $row = $q->row();

    // You can now utilize $row->emp_id to insert into another table
    $ID = $row->emp_id;
} else {
    $this->session->set_flashdata('message','Employee ID does not exist');
    redirect("admin_logins/meal");
}

Questioning why emp_id is stored as varchar in the meal table? It would be beneficial if the types were aligned, and using int is more efficient when matching (joining tables).

Answer №2

Implemented significant revisions:

Controller -

function meal2()
{
    if($_POST)
    {
        date_default_timezone_set('Asia/Dacca');
        $temp = $this->input->post('emp_id');

        $query = $this->db->query("SELECT id FROM employee WHERE emp_id = '$temp' ")->result_array();

        $mdata['emp_id'] = $query[0]['id'];

        if($mdata['emp_id'] == '')
        {
            $this->session->set_flashdata('message','Employee ID doesn't exist');
            redirect("admin_logins/meal");
        }


        $mdata['entry_date'] = date('Y-m-d');
        $mdata['is_guest'] = $this->input->post('is_guest_checkbox');
        $mdata['num_of_guest'] = $this->input->post('num_of_guest');

        $mdata['remarks'] = $this->input->post('remarks');

        $res = $this->meal_model->insert_meal($mdata);
        if($res)
        {   
            $this->session->set_flashdata('message','Meal information added successfully');
            redirect("admin_logins/meal");
        }
    }
    else
    {
        $this->load->view('admin_logins/meal_add');
    }

}

Another method named meal() in the controller includes:

    $data['myQuery'] = $special_query = $this->db->query("SELECT m.id, e.emp_id, m.entry_Date, m.is_guest, m.num_of_guest, m.remarks FROM meal m LEFT JOIN employee e ON e.id = m.emp_id")->result_array();

Incorporated a LEFT JOIN to fetch related information efficiently.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modify information on the user interface without the need to refresh the page

Is there a way to update data on the UI without having to refresh the screen in a web application built with Node.js? I'm looking to make only specific changes on the screen. Additionally, how can I ensure that the data displayed on the screen is upda ...

Integrating a fresh element into the carousel structure will automatically generate a new row within Angular

I'm currently working on an Angular4 application that features a carousel displaying products, their names, and prices. At the moment, there are 6 products organized into two rows of 3 each. The carousel includes buttons to navigate left or right to d ...

Troubleshooting: Issue with Angular 2 bidirectional data binding on two input fields

Hi there, I am encountering an issue with the following code snippet: <input type="radio" value="{{commencementDate.value}}" id="bankCommencementDateSelect" formControlName="bankCommencementDate"> <input #commencementDate id="bankCommencementDat ...

Jquery Triggers Failing to Work Following Ajax Request

I have worked on 2 PHP pages, called "booking.php" and "fetch_book_time.php". Within my booking.php (where the jquery trigger is) <?php include ("conn.php"); include ("functions.php"); ?> $(document).ready(function(){ $(".form-group"). ...

Continuous scroll notification within the fixed menu until reaching the bottom

I'm looking to achieve a scrolling notification message that stays fixed at the bottom of a top-fixed menu while the body content continues to scroll normally. Here's an example in this fiddle: HTML: <div class="menu-fixed">I am a fixed me ...

Creating a private variable to perform a select_sum query

I have defined private variables in my CodeIgniter code like this: private $table = 'phone'; private $column_order = array(null, 'name', 'price'); private $type = array('type'); private $battery_consumption = array ...

Enable the feature for users to upload images to a specific folder within the Chrome extension without the need for

I need to implement a feature in my Chrome extension that allows users to upload images directly to a specific folder named "upload" without needing a submit button. <form action="/upload"> <input type="file" name="myimages" accept="image/*"> ...

Mastering Yii2: Implementing Javascript Functions such as onchange() in a View

One of the elements in my project is a checkbox: <div class="checkbox"> <label> <?= Html::checkbox('chocolate', false) ?> Chocolate </label> </div> In addition to that, I also have a span ta ...

Having trouble with a JavaScript function as a novice coder

Hello, I'm still getting the hang of JavaScript - just a few days into learning it. I can't figure out why this function I'm calling isn't functioning as expected. Here's the content of my HTML page: <!doctype html> <htm ...

Step-by-step guide to creating a transition effect when the input changes

I'm looking to add a unique effect to my dropdown menu My goal is to create an effect in which the placeholder moves up and the new value seamlessly takes its place, using JS, jQuery, CSS, and HTML. View before transition View after transition ...

Having trouble with selecting checkboxes in a div using jQuery? While it may work in IE and Firefox, Chrome seems to be causing issues

In my div, I have several checkboxes placed under labels for formatting purposes. There is a list of checkbox names that need to be checked upon certain actions. Here is the list: var columns= ['2','5','4'] This is the curren ...

The event listener function is not functioning properly on images generated by JavaScript

I'm currently working on placing multiple images on a grid in the center of the page and would like to include a function that triggers when each individual image is clicked. The images are dynamically created using JavaScript and inserted into the do ...

The symbol "#" appears in my URL whenever the link is clicked

Seeking guidance on a URL issue that I am facing. Whenever I click the source link, it adds a pound sign to the URL. How can I prevent this from happening? Can someone assist me in identifying the necessary changes required in my jQuery or HTML code? Bel ...

Utilizing Bootstrap Modal to Display PHP Data Dynamically

Modals always pose a challenge for me, especially when I'm trying to work with someone else's code that has a unique take on modals that I really appreciate (if only I can make it function correctly). The issue arises when the modal is supposed ...

Is it illegal to escape quotes when using an image source attribute and onerror event in HTML: `<img src="x" onerror="alert("hello")" />`?

Experimenting with escape characters has been a fascinating experience for me. <img src="x" onerror=alert('hello'); /> <img src="x" onerror="alert(\"hello\")" /> The second code snippet triggers an illegal character error ...

The Bootstrap 4 card component is a versatile and stylish

Currently working on a display layout using Bootstrap 4, specifically utilizing cards. The issue I'm facing is that the text exceeds the limit of the card, causing it to overflow. Is there a solution to make the text automatically wrap to the bottom ...

Using AJAX to submit a form to a CodeIgniter 3 controller

I am working on adding a notification feature and need to run an ajax query through the controller when a button is clicked. Here's the script I'm using: $('#noti_Button').click(function (e) { e.preventDefault(); ...

The NPM Install process seems to be skipping certain files that were successfully installed in the past

When I first installed NPM Install in a folder, it created multiple folders and files: node_modules public src .DS_Store package.json package-lock.json webpack.config.js After that, npm start functioned perfectly. Now, as I embark on a new project for th ...

Hiding a specific tag with vanilla JavaScript based on its content

I am facing a challenge with my code that is supposed to hide div elements containing a specific word along with additional text. I have tried multiple solutions but none seem to work effectively. Any assistance on how to hide divs properly will be greatl ...

Convert text into a clickable link

Creating a form with numerous text fields, some of which require numerical input. The main goal is to have users enter a tracking number, order number, or any other type of number that, when submitted, will open a new URL in a separate window with the spec ...