Unable to present the information due to a codeigniter error in retrieving the data

Encountering an issue where the data cannot be displayed and it's showing an error message of undefined variable: avg. Below is the script being used:

The controller function:

public function rate_config() {
        $rt = $_POST['hasil_rating'];
        $content["hasil_rating"] = $rt;

        $this->db->insert("tb_rating", $content);
        redirect("rate/index?status=tambah_success","refresh");

        $data['avg'] = $this->db->select_avg("hasil_rating")
                                ->get("tb_rating");
        $this->load->view('rating', $data);
}

And here is the view code:

<form method="post" action="<?php echo base_url('rate/rate_config');?>" enctype="multipart/form-data">
    <input class="rating" name="hasil_rating" data-stars="5" data-step="0.5">
    <div class="form-group" style="margin-top:10px">
        <button type="submit" class="btn btn-success">RATE</button>
    </div>
    <div>
</form>
        <label class="label label-primary"><?=$avg['hasil_rating']?></label>
    </div>
<hr>

The $avg['hasil_rating'] is supposed to display the data from $data['avg'].

Considering whether or not a model should be used in this case, as currently there isn't one in place which might save time. Any advice would be appreciated.

Answer â„–1

When writing your code:

    public function calculate_rating() {
    $rating = $_POST['user_rating'];
    $data_to_insert["user_rating"] = $rating;

    $this->db->insert("ratings_table", $data_to_insert);

    /*==================Important Note====================*/
    redirect("calculate/index?status=add_success","refresh");

    $data['average'] = $this->db->select_avg("user_rating")
                            ->get("ratings_table");
    $this->load->view('display_rating', $data);
   }

It seems that you have initiated the redirect before calculating the average rating. Please consider adjusting the order of operations for better functionality.

Answer â„–2

Initially, you encountered an issue with sending data to the view because the redirection was executed before sending the data.

Furthermore, to retrieve results from the database, please refer to the following link:

https://www.codeigniter.com/user_guide/database/results.html?highlight=result

This resource provides a comprehensive explanation along with examples.

If you wish to fetch a single result row, you can use the following methods,

row() // it returns an object.
row_array // it returns an array

For example,

$data['avg'] = $this->db->select_avg("hasil_rating")
                            ->get("tb_rating")->row_array();

Lastly, you can either delete or uncomment the following line.

//redirect("rate/index?status=tambah_success","refresh");

Answer â„–3

Here's a recommendation for you.

To fully utilize the capabilities of the Codeigniter framework, it is advisable to use models for database operations. Make sure to explore all the features that Codeigniter offers.

I suggest going through the documentation for more in-depth information.(https://www.codeigniter.com/user_guide/)

After reviewing your code, I noticed that you missed fetching the result. Using result_array() allows you to retrieve multiple rows in an array format.

$data['avg'] = $this->db->select_avg("hasil_rating")->get("tb_rating")->result_array();

When displaying:

 echo $avg[0]['hasil_rating'];

If it is a single row, then use row(), which returns the result as an object.

$data['avg'] = $this->db->select_avg("hasil_rating")->get("tb_rating")->row();

For displaying:

echo $avg->hasil_rating;

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

Ensure tables are vertically centered when printing an HTML page

I need to export two tables, each measuring 7cm×15cm, to a PDF file with A4 portrait paper size using the browser's "Save to PDF" option in the print tool. My goal is to center these two tables vertically on the A4 paper. If that proves difficult, I ...

Having trouble rendering the response text from the API fetched in Next.js on a webpage

I've written some code to back up a session border controller (SBC) and it seems to be working well based on the output from console.log. The issue I'm facing is that the response comes in as a text/ini file object and I'm unable to display ...

Guide to adding an icon within an HTML `<input>` element

Is anyone able to help me successfully place my icon font inside the search input field? I've tried adjusting the margin and padding, but nothing seems to be working! If you have any insights or suggestions, please let me know. Your help is greatly a ...

The div element is failing to adjust its height correctly to match its parent container

I'm struggling to make the red border that wraps around the text extend all the way to the bottom of its parent div. Setting the height to 100% isn't achieving the desired effect, as it needs to match the height of the image. Tip: Try resizing y ...

Say goodbye to <!DOCTYPE html> when using htmlAgilityPack

I'm currently developing an app for WP 8.1, and one of the tasks I need to accomplish is parsing a webpage with the following structure: <!DOCTYPE html> <html> <body> <table cellspacing="0" cellpadding="0" border="0" style="b ...

Issue "It seems like the mysql extension required by wordpress is missing in your php installation" encountered on Ubuntu 18.0.4 with PHP version 7.2

After upgrading my Ubuntu version from 16.04 to 18.0.4 and updating PHP to 7.2, I encountered a problem trying to log in to my Wordpress websites. The specific error message reads: Your php installation appears to be missing the mysql extension which is ...

Adding text to a Video Js fullscreen window on an iPad

Looking to enhance user experience on iPad while using a video js player, I want to make an image pop up upon completion of the video. Currently, I have it set up to work without full screen mode, but iPad users prefer watching videos in full screen. Is th ...

Utilize the div element to segment a webpage into four different sections

Within a div tag, I have used 4 other div tags to create equal areas. Is there an alternative method to achieve this division or improve it? <div style="width: 689px; margin-left: 215px; margin-top: 0px; float: none; height: 502px;"> ...

What is the best way to display a SolidJS component on the screen?

I am currently working on a unique menu design for my application. The concept involves rendering a functional component within an element created in the body using createRoot and render methods. https://i.stack.imgur.com/g6Ofv.png export function create ...

I am working on an HTML form that is designed vertically, but I am unsure of how to arrange two text fields side by side on the same line

I'm struggling with formatting my HTML form to have two text fields on the same line instead of stacked vertically. In the example below, I want the Size, Width, and Height fields to be aligned horizontally rather than one below the other. <form c ...

Using the "if else" statement in a jQuery AJAX response

I have an Ajax function that is functioning correctly, but I want to display a different message when the Ajax response is: <h3>No Couriers found near you. Please select another location.</h3> If I receive this specific response, I want to sh ...

Tips for arranging 3 tables in the right place using CSS

I have 3 tables that I utilize. My goal is to: have one on the left side of the page place one in the center of the page position one on the right side All at the same height. The issue arises when the tables expand and using float causes them to ...

How can I add information into a nested div element?

I encountered an issue when attempting to insert data into my block. The div structure is as follows: <div class="1"> <div class="2"> <div class="3"> <div class="4"></div> </div> ...

Event Triggering in CakePHP

I am struggling with the onChange event in this code snippet. I must have overlooked something because it's not functioning as expected. Can someone please point out my mistake? Your assistance is greatly appreciated: <td class="cellInput"> & ...

Do not open iframe links in a new window

Is it possible to manipulate the iframe so that links open inside the iframe window? I want the links clicked within the iframe to stay within the same window instead of opening in a new one. However, I have too many links to individually edit their code ...

Making changes to HTML on a webpage using jQuery's AJAX with synchronous requests

Seeking assistance to resolve an issue, I am currently stuck and have invested a significant amount of time. The situation at hand involves submitting a form using the traditional post method. However, prior to submitting the form, I am utilizing the jQue ...

Which DocType is most suitable for my web application?

I'm grappling with the HTML and XHTML specifications, and I can't decide which one to go for. Can you help me understand which is better? For instance, if I have a web application in PHP that searches an image database and displays results dynam ...

Is BEM mandating the creation of superfluous elements?

<header> <a href="#"><img src="kitty.jpg" /></a> ... </header> In the context of organizing for BEM, take this example within the header section that is not dependent on the header block. To adhere to BEM guidelines, I op ...

What are the steps to integrate <br> in a JavaScript code?

I have recently started learning about web development and I'm facing a challenge with this implementation. var obj = [[{ name: "John", age: 30, city: "New York"}, { name: "Ken", age: 35, city: "New Orleans"}]]; ...

What is the best way to dynamically insert columns into HTML code?

This is an example of my HTML code: <div class="row text-center"> <div class="col h4">We Collaborate With:</div> <div class="col">company1</div> <div class="col">company2</div> ...