Display the json encoded result of a MySQL SUM() query

I am attempting to use JSON to print the total sum of a price.

Here is my current approach:

$query="SELECT SUM(cost) FROM `Service`";
$result = mysql_query($query);

$json = array();
    while($row = mysql_fetch_array($result))
    {
            $json['cost'] = $row['cost'];
    }
    print json_encode($json);
mysql_close();

However, this is returning null.

If I change the query to SELECT cost FROM Service, it only returns the last cost from the database.

Could someone please point out what mistake I am making here?

Answer №1

Assign a new name as an ALIAS to the column used in the aggregate function

SELECT SUM(cost) as totalCOST FROM `Service`

This allows you to retrieve the value by the new name

$json['cost'] = $row['totalCOST'];

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

Tips on converting a Java regular expression to JavaScript regular expression

Can someone assist me in translating the Java Regex code below to JavaScript Regex? (\\\p{Upper}{2})(\\\d{2})([\\\p{Upper}\\\p{Digit}]{1,30}+) I attempted using the following JavaScript Regex: ...

Choosing the following choice using the Material-UI Select tool

Looking for a way to enhance my dropdown select from MUI in a Nextjs application by adding two arrows for navigating to the next/previous option. Here's what my code currently looks like: <StyledFormControl> <Select value={cu ...

Exploring Node.js and JSON: Retrieving specific object attributes

Utilizing ExpressJS, NodeJS, and Bookshelf.js In an attempt to display a user's list of friends, encountering the error "Unhandled rejection TypeError: Cannot read property 'friends' of undefined" when trying to access a property of the obj ...

My data table includes a column that holds API requests with special characters, giving it a unique appearance

{ "Data": { "code": "SPPACK" }, "person": { "firstName": "Jane", "lastName": "Doe", "access": { "loginType": "EMAIL_ADDRESS ...

The $.ajax request encounters an error when trying to parse the data as JSON

I am encountering an issue where my ajax call to a JSON file fails when using dataType: "json". However, changing it to "text" allows the ajax call to succeed. See the code snippet below: $.ajax({ type: "POST", url: url, dataType: "json", ...

Customizable form fields in AngularJS

Consider the scenario of the form below: First Name: string Last Name: string Married: checkbox % Display the following once the checkbox is selected % Partner First Name: Partner Last Name: [Submit] How can a form with optional fields be created in Angu ...

A guide on accessing objects from an array in Vue.js

Wondering how to choose an object from an array in Vue.js: When the page loads, the selectTitle() function is triggered. I simply want to select a specific object (for example, i=2) from my 'titleList' array. However, at the moment, I am only re ...

Transferring data using AJAX between an AngularJS frontend and a Node.js backend

Just a heads up: The main question is at the bottom in case you find this post too lengthy ;) I'm currently working on developing my first angularjs app and I've hit a roadblock when it comes to fetching data via ajax from my nodejs (express) se ...

Using JavaScript's Regex to match sentences, while ensuring any full stops within quotes are ignored

Here is the regular expression: (?:(?:Jr|Master|Mr|Ms|Mrs|Dr|Capt|Col|Sgt|Sr|Prof|Rep|Mt|Mount|St|Etc|Eg)\.\s+|["'“(\[]?)(?:\b(?:(?!(?:\S{1,})[.?!]+["']?\s+["']?[A-Z]).)*)(?:(?:(?:Jr|Master|Mr|M ...

Issue encountered when trying to retrieve a database variable from a mapReduce operation in MongoDB

Greetings! I am currently developing an application that utilizes a MongoDB database. Within this database, there exists a user collection where all user data is stored. The structure of a document in this collection is as follows: { "_id" : ObjectId( ...

What in the world is going on with this code snippet? I'm completely stumped on how to fix this problem

Attempting to generate a custom element with unique properties function y(){ var g=document.createElement("div"); this.label="elephant"; return g; } y.prototype.customFunction=function(){ alert(arguments[0]+this.label); }; var b=new y(); b ...

Running a local project with the help of the Express framework

// Setting up the configuration for serving files from the source directory var express = require('express'); // Importing express module var path = require('path'); // Importing path module var open = require('open'); // Imp ...

Using an array to dynamically input latitude and longitude into a weather API call in PHP

I am currently working on a leaflet map project that showcases the top 10 cities in a selected country. The markers are added dynamically based on the coordinates provided in the $latLng array. For example, when Australia is chosen from the select field, t ...

Output each value of a specific node individually from a JSON response using Groovy scripting

Received a JSON response from a web service: { "status" : true, "statusCode" : "OK", "requestId" : "b9c0ffe3-2b62-465d-bc0f-48a1279c3a54", "responseData" : { "ResDoc" : { "education" : { "#text" : ["EDUC ...

I am currently using React to implement a feature that displays random facts for 5-second intervals. Despite no errors being displayed, the facts are not appearing on the page as expected

Client side My react application includes a section that is supposed to display random facts at 5-second intervals. Although no errors are displayed, the facts do not appear on the page when I run the code. import React from "react"; import &quo ...

Integrate fullCalendar event creation with Spring MVC using an AJAX request

I am looking to integrate a new event into fullCalendar and send this event as a JSON object to the server side, which is running on SpringMVC, through an AJAX request. However, every time I make the request, I receive a "400 Bad Request" response. Here i ...

Retrieve data from a div element on a webpage using specific parameters

As I work on a form that includes various filters and a "Start" button in C# / ASP.NET MVC, my goal is to display database data in a partial view using Ajax when the button is clicked, based on certain parameters. Within this partial view, there is a link ...

What is the best way to determine which CSS class is shown when the page is loaded using JQuery?

I am facing a dilemma with displaying my site logo. I have both an image version and a text version, and I want to choose which one to display based on the vertical position on the page and the screen width. <a class="navbar-brand" id="top-logo" href=" ...

Ways to troubleshoot JavaScript following an AJAX request?

My webpage is structured into three separate files. The index.html file contains a navigation bar, a content box, and a footer within 3 divs. Additionally, there are two other .html files with different content that should load upon clicking specific links ...

Encountering ECONNREFUSED error when making requests to an external API in a NextJS application integrated with Auth

Currently, I have integrated Auth0 authentication into my NextJS application by following their documentation. Now, I am in the process of calling an external ExpressJS application using the guidelines provided here: https://github.com/auth0/nextjs-auth0/b ...