Reputation: 33
I am trying to read data from MySql
with PHP
and then send results with json_encode
to client. I am then using jQuery
script to read the results but unable to index the columns in the JSON
because of the type of name given to the column has brackets in it COUNT(ID)
.
I am trying to learn several things at once, jQuery
, SQL
etc and think there must be a better/easier way?
I have made a SQL
query to count the number of times a name appears in one of the columns. It returns a column name COUNT(ID)
...
SQL query:
SELECT COUNT(ID), LocationName FROM myDB GROUP BY LocationName'
jQuery
reading the JSON
into arrays:
for(var i in data)
{
getProfileName.push = data[i].ProfileName;
getLocationCount.push = data[i].COUNT(ID)
}
I receive the JSON
in my jQuery
script, and it has the 2 columns LocationName
and COUNT(ID)
But obviously I cannot use the index name of COUNT(ID)
because of the brackets.
How do you reference names with brackets?
Upvotes: 3
Views: 58
Reputation: 72299
You need to give an alias for COUNT(ID)
in your query, something like below:
SELECT COUNT(ID) as totalIdCount, LocationName FROM myDB GROUP BY LocationName
//------------------^you can chang alias name according to your comfort --------//
Now use this alias in jQuery
for(var i in data)
{
getProfileName.push = data[i].ProfileName;
getLocationCount.push = data[i].totalIdCount
}
Note:- you can try data[i]['COUNT(ID)']
directly in your jQuery code, but above is the standard practice.
Upvotes: 2