vote up 0 vote down star

Hi i'm working on some code with mysql and need to display the mysql results with php..

MySQL
select distinct(year(Cataloged_Date)) from records;

+------------------------+
| (year(Cataloged_Date)) |
+------------------------+
|                   2009 |
+------------------------+
1 row in set (0.00 sec)


PHP

foreach($query->result() as $show){
    			$data[$i] = $show->Cataloged_Date;
    			$i++;
    		}

I'm using codeigniter for the php. Using $show->Cataloged_Date will not return anyting. I'm thinking its $show-> something to display the results...Just cant get it right now...

flag

3 Answers

vote up 2 vote down

You need to provide a explicit name or alias for your field in the mysql query - when you apply functions to a column then it's non-obvious what the column name will be.

link|flag
vote up 1 vote down

Try this:

//on MySQL
select distinct(year(Cataloged_Date)) as "Cat_Date" from records;

<?php
  foreach($query->result() as $show){ 
    $data[$i] = $show->Cat_Date; 
    $i++; 
  }
?>

You can apply an alias to any "value" on your select, be it a column name or the result of a function.
Just do

SELECT something AS YourAlias ...

To give you a clear example:

mysql> select 1;
+---+
| 1 |
+---+
| 1 |
+---+
1 row in set (0.00 sec)

#A simple value can be given an alias
mysql> select 1 as "Number";
+--------+
| Number |
+--------+
|      1 |
+--------+
1 row in set (0.00 sec)

mysql> select max(val) from my_values;
+----------+
| max(val) |
+----------+
|        4 |
+----------+
1 row in set (0.00 sec)

#A function
mysql> select max(val) as "max_val" from my_values;
+---------+
| max_val |
+---------+
|       4 |
+---------+
1 row in set (0.00 sec)

#or even a plain column
mysql> select val as "lav" from my_values;
+------+
| lav  |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
+------+
4 rows in set (0.00 sec)
link|flag
That absolutely worked...Thanks a mill.... – Fabian Glace 2 days ago
You're welcome! Just make sure you give upvotes to those answers that helped you as well as pick one of them as your "accepted answer". – Carlos Lima yesterday
vote up -1 vote down

Yes this is normally true but i'm using Codeigniter php framework. I did get it working with "$query->first_row() as $show"

then just echo $show and the results will display without you needing to know the rows name..

link|flag
1  
Well, that doesn't have a lot to do with CodeIgniter framework - we can easily avoid column names in vanilla php too. However, given your code example $show->Cataloged_Date, the reason I gave is the correct reason. – BrynJ Nov 25 at 22:54

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.