views:

92

answers:

3

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...

+2  A: 

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.

BrynJ
A: 

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..

Fabian Glace
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
+1  A: 

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)
Carlos Lima
That absolutely worked...Thanks a mill....
Fabian Glace
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