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'];
}
Related
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.
I have a table names and in that table there is a field info data is like this:
ID info
1 'alpha,romeo,ciera,delta'
2 'testing,temp,total'
I am trying to create a select query.
select * from names where info like '%$var%'
$var is data from php.
Problem is i want exact match. If i use above query and in $var if
data is rome then it also return row of romeo.
one more example-
data in table is testing,temp,total
user input data is test then it also return testing
i tried
select * from names where info like '$var%'
and
select * from names where info like '%$var'
but it didn't return data as i expected.
Please advise how can i achieve this.
Note- : This is an example i am not using mysql as its depreciated. I am using mysqli
Append , at begin and end of your target search string.
And then make sure your source string also has those ,
SQL Fiddle Demo
select *
from names
where concat( ',', info , ',') like
concat( '%,', $var, ',%')
The problem is this wont use any index. You should go for FULL TEXT search
Problem is i want exact match. If i use above query and in $var if data is rome then it also return row of romeo.
Don't use the LIKE operator, use exact match operator =
select * from names where info = '$var'
Use , in your query to use it as a delimiter and use multiple conditions to account for the "edge cases".
SELECT *
FROM names
WHERE
info LIKE '%,$var,%' OR
info LIKE '$var,%' OR
info LIKE '%,$var' OR
info = '$var'
If you have rows with info column:
alpha,romeo,ciera,delta
testing,temp,total
rome
foo,test,bar
berlin,paris,madrid,london,rome
venice,milano,rome,firence
black,crome
rome,fome,mome,kome,kome
Query with $var as "rome" will select:
rome
berlin,paris,madrid,london,rome
venice,milano,rome,firence
rome,fome,mome,kome,kome
But not:
alpha,romeo,ciera,delta
black,crome
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");
first of all, that's what I'm trying to do:
In one of my classes in the library I want to count the total amount of rows of a search result. The class uses a select object set by the appendant model of the search result. My problem is now, this select() has already set the requested columns by from(), but to simply count the rows I just want to select the id, because the website has to to be performant. I can't simply change the values of the object, because I'm using it in the library and the variables are protected. Unfortunately, Zend has no function for the mySql count command and I don't want to use static mySql code, because it could be, that we switch our database system in the future.
Now here's my question:
Is there any possibility by Zend_Select how I could change the selected columns?
Try this:
$select->reset(Zend_Db_Select::COLUMNS)
->from('thetable', 'COUNT(*)');
replacing the 'thetable' with the correct table name.
This is from a project and isn't tested, but one of these should work.
$select->from(array("table_name" => "table_name"), array("my_col" => "COUNT(id)"));
OR
$select->from(array("table_name"), array("my_col" => "COUNT(id)"));
This is the same as
SELECT COUNT(id) as my_col FROM table_name
Hope that helps
Jake
This one didn't work for me (I needed to select only from one joined table):
$select->reset(Zend_Db_Select::COLUMNS)
->from('thetable', 'COUNT(*)');
Maybe because I had some joins. But nevertheless, here's the solution: to use reset() and then columns():
$select->setIntegrityCheck(false)
->from(['t1' => 'table1'])
->join(['t2' => 't2'], 't1.id = t2.t1_id')
->reset(Zend_Db_Select::COLUMNS)
->columns('t1.*');
Just FYI, the version of Zend Framework is 1.12
To use a mysql command in a select, you need to use Zend_Db_Expr:
$select = $this->select()
->from('myTable', new Zend_Db_Expr('COUNT(id) as count'));
echo $select; //SELECT COUNT(id) as count FROM myTable;
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;