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?
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.
Related
I have a sql result that looks like this:
MAX(val) | instance
17410742.00 | 0
I need to loop through it in php but I can't seem to select the Max(val) column. Usually I would do a something like this:
foreach ($sqlmax as $maxrow){
$myvar=$maxrow['instance'];
}
Which returns the 'instance' value, but I can't get the syntax to retrieving the Max(val) as
foreach ($sqlmax as $maxrow){
$myvar=$maxrow['Max(val)'];
}
doesn't work. I get the error Notice: Undefined index:
How do I select the Max(val) result in the same way I can select the 'instance' value? Thanks
Use AS in your SQL Query:
SELECT MAX(val) AS max_val, instance FROM table WHERE instance = 0;
Then you will be able to access the column as $myvar=$maxrow['max_val'];.
The query I wrote here is just an example, since you do not provide yours.
I will go ahead an assume you use mysql and will provide a link to MySQL docs:
A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses. For example:
SELECT CONCAT(last_name,', ',first_name) AS full_name FROM mytable ORDER BY full_name;
Assign a column name in your query, so you can access the field easier:
SELECT MAX(val) AS max_value ....
Then you can access it with
$myvar=$maxrow['max_value']
Simply do it like
select max(val) as mval
and access it like
$maxrow['mval']
Just providing an alternate answer, in case you don't want (or are unable to) use AS.
The problem here was that the key of the array is case sensitive, so you have to use $maxrow['MAX(val)'] instead of $maxrow['Max(val)'].
SELECT MAX(val) AS instance
Access this
foreach ($sqlmax as $maxrow){
$myvar=$maxrow['instance'];
}
Hopefully I'm going about this the right way, if not I'm more than open to learning how this could be done better.
I need to pass a comma separated list of integers (always positive integers, no decimals) to a stored procedure. The stored procedure would then use the integers in an IN operator of the WHERE clause:
WHERE [PrimaryKey] IN (1,2,4,6,212);
The front-end is PHP and connection is made via ODBC, I've tried wrapping the parameter in single quotes and filtering them out in the stored procedure before the list gets to the query but that doesn't seem to work.
The error I'm getting is:
Conversion failed when converting the varchar value '1,2,4,6,212' to data type int.
I've never done this before and research so far has yielded no positive results.
Firstly, let's use a SQL Function to perform the split of the delimited data:
CREATE FUNCTION dbo.Split
(
#RowData nvarchar(2000),
#SplitOn nvarchar(5)
)
RETURNS #RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
Declare #Cnt int
Set #Cnt = 1
While (Charindex(#SplitOn,#RowData)>0)
Begin
Insert Into #RtnValue (data)
Select
Data = ltrim(rtrim(Substring(#RowData,1,Charindex(#SplitOn,#RowData)-1)))
Set #RowData = Substring(#RowData,Charindex(#SplitOn,#RowData)+1,len(#RowData))
Set #Cnt = #Cnt + 1
End
Insert Into #RtnValue (data)
Select Data = ltrim(rtrim(#RowData))
Return
END
To use this, you would simply pass the function the delimited string as well as the delimiter, like this:
SELECT
*
FROM
TableName
WHERE
ColumnName IN (SELECT Data FROM dbo.Split(#DelimitedData, ','))
If you still have issues, due to the datatype, try:
SELECT
*
FROM
TableName
WHERE
ColumnName IN (SELECT CONVERT(int,Data) FROM dbo.Split(#DelimitedData, ','))
You can pass a comma separate list of values. However, you cannot use them as you like in an in statement. You can do something like this instead:
where ','+#List+',' like '%,'+PrimaryKey+',%'
That is, you like to see if the value is present. I'm using SQL Server syntax for concatenation because the question is tagged Microsoft.
This code is used to get a specific list of ID's from one table, then use those ID's to get the information from another table. Once I get all the information from the 2nd table, I am attempting to sort the data alphabetically based on a field in the 2nd table.
Example, I am getting the name based on a correlating ID and then want to display the entire result in alphabetical order by name (artist_name).
Here is the code I have. When I execute this without the sort(), it works fine but is not in alphabetical order. When I add the sort() in the 2nd while statement, the page looks the same but the name and other data do not display. The source code in the browser shows that the results are being accounted for but the sort must be preventing the variables or information from being displayed for some reason.
I haven't used a sort function before and I tried looking at some examples but couldn't really find something specific to my situation. Any and all help would be greatly appreciated. I have already looked at the PHP manual for sort so no need to send me a link to it ;-)
<?php $counter = 0;
$artistInfo = mysql_query("SELECT DISTINCT event_url_tbl.artist_id FROM event_url_tbl WHERE (SELECT cat_id FROM artist_tbl WHERE artist_tbl.artist_id = event_url_tbl.artist_id) = 1");
while ($aID = mysql_fetch_array($artistInfo))
{
$getArtistInfo = mysql_query("SELECT * FROM artist_tbl WHERE artist_id = '" . $aID['artist_id'] . "'");
while($artist = mysql_fetch_array($getArtistInfo))
{
sort($artist);?>
<a class="navlink" href="<?=HOST?><?=$artist['page_slug']?>/index.html">
<?=$artist['artist_name']?>
</a><br />
<?php }
}
?>
Your best bet, as a commenter mentioned, is to use an ORDER BY clause in SQL.
SELECT *
FROM artist_tbl
WHERE artist_id = XXX
ORDER BY artist_name ASC
The other commenter who suggested using PDO or mysqli is also correct, but that's a different issue.
To answer your specific question about sorting, according to the manual,
Blockquote Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.
This means all of your array keys ('page_slug', 'artist_name', etc) are wiped out. So when you try to refer to them later, there is no data there.
Were you to use this method, you would want to use asort to sort an associative array.
However, you don't want to use sort here. What you're sorting is the variables for one row of data (one individual artists), not all of your artists. So if you think of each artist row as an index card full of data (name, id#, page slug, etc) all you're doing is moving those items around on the card. You're not reorganizing your card catalog.
Using an order by clause in the SQL statement (and rewriting in PDO) is your best bet.
Here is how I would rewrite it. I have to take some guesses at the SQL because I'm not 100% sure of your database structure and what you're specifically trying to accomplish, but I think this would work.
$query_str = "
SELECT
artist.name,
artist.page_slug
FROM
artist_tbl AS artist
INNER JOIN event_tbl AS event
ON event.artist_id = artist.artist_id
WHERE
artist.cat_id = 1
ORDER BY
artist.name ASC";
$db_obj = new PDO (/*Connection stuff*/);
$artists_sql = $db_obj->prepare ($query_str);
$artists_sql->execute ();
while ($artist = $artists_sql->fetch (PDO::FETCH_ASSOC)) {
$return_str .= "<a class='navlink' href='{HOST}
{$artist['page_slug']}/index.html'>
{$artist['artist_name']}</a><br/>";
}
echo $return_str;
In all honesty, I would probably create an artist class with a display_link method and use PDO's fetchObject method to instantiate the artists, but that's getting ahead of ourselves here.
For now I stuck with procedural code. I don't usually like to mix my HTML and PHP so I assign everything to a return string and echo it out at the end. But this is close to what you had, using one SQL query (in PDO - seriously worth starting to use if you're creating new code) that should give you a list of artists sorted by name and their associated page_slugs.
You could do all of this in one query:
SELECT * FROM event_url_tbl AS event
INNER JOIN artist_tbl AS artist ON event.artist_id = artist.id
ORDER BY artist.name DESC;
This cuts out a lot of the complexity/foreaches in your script. You'll end up with
Label1 (Label 1 details..) Artist1 (Artist1 details..)
Label1 (Label 1 details..) Artist2 (Artist1 details..)
Label2 (Label 2 details..) Artist3 (Artist1 details..)
Always good to bear in mind "one query is better than many". Not a concrete rule, just if it's possible to do, try to do it. Each query has overheads, and queries in loops are a warning sign.
Hopefully that helps
I would expect the following to output the number "5", since there are 5 rows in the database with with item 68 and user 1. But instead I'm getting this output "12345".
$resultb4 = mysql_query("SELECT COUNT(comparedRating) FROM recComparedRating WHERE user1='1' AND itemID='68' GROUP BY itemID AND user1");
while($rowb4 = mysql_fetch_array($resultb4)){
$countcomparedratings=$rowb4['COUNT(comparedRating)'];
}
echo $countcomparedratings;
What am I doing wrong?
The reason you are getting 12345 is because your query is returning 5 results and your code to output the count is simply outputting the concatenation of the returned array from the query.
Without understanding your database structure, I'm guessing that the reason you're getting the '12345' has something to do with your GROUP BY clause. Use a program like MySQLWOrkbench to connect to your database and test out your query before you include it into your code. It is a time saving technique to debug your queries.
Also, I would alias the COUNT value so that you simply refer to the alias when you refer to your column names.
SELECT COUNT(comparedRating) as ratingCount FROM recComparedRating WHERE user1='1' AND itemID='68' GROUP BY itemID AND user1");
how doHow do we do
select table.value as table_value from table in codeigniter?
The AS part doesnt work because when i try to access the value,
this doesnt work:
$qry_inp = 'select table.value as table_value from table '
$query = $this->db->query($qry_inp);
echo $query->row('table_value ');// this will be empty, but it shouldn`t be
doesn`t matter if its in AR or simple query
Pretty simple thing.
$this->db->select('COLUMN_ACTUAL_NAME as `COLUMN_NAME_YOU_WANT_TO_SHOW`');
i'm joining two tables in which column names are same so i separate both tables columns by using as keyword , this is how you can use AS in codeigniter
$this->db->select("departments.name AS 'dname'");
$this->db->select('positions.name');
Where is that behaviour documented? row doesn't take a column name as a parameter; it optionally takes a row number, and that's it. Access it like any other field:
echo $query->row()->table_value;