Page 1 of 1

alternate field header names in website

Posted: Sun Nov 22, 2009 10:52 pm
by thadson
Here is a basic "print out my table" script:

Code: Select all

 
<?php
session_start();
require_once('inc/constant.php');
require_once('inc/function.php');  //basic functions
db_on();
 
$table = 'mytable';
 
// sending query
$sql = "SELECT `name`, `yesterday`, `today`, `difference`, `quota`, `date` FROM {$table} WHERE `active` = 1 ";
$res=mysql_query($sql,_sql); //_sql is my link to the db definened in funtions.php
if (!$res) {
    die("Query to show fields from table failed");
}
 
$fields_num = mysql_num_fields($res);
 
echo "<table border='1' align='center'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
    $field = mysql_fetch_field($res);
    echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
$i=0; 
  while($row = mysql_fetch_row($res)){  
echo "<tr>"; 
      if (($i%2)==0){  
//        if (($temp) < 0){
      foreach($row as $cell)  
echo "<td><font color='FF0000'>$cell</font></td>"; 
      } 
      else{  
        foreach($row as $cell)  
echo "<td><font color='0000FF'>$cell</font></td>"; 
      } 
    $i++;  
echo "</tr>\n"; 
  }
mysql_free_result($res);
?>
 
How can I display an alternate field name for my columns? What do I need to change?

Like if I want to have the field 'name' displayed as "Name" in the table header row,
the field 'yesterday' displayed as "As of Yesterday"
'today' as "As of Today"

Re: alternate field header names in website

Posted: Sun Nov 22, 2009 11:01 pm
by requinix

Code: Select all

SELECT `name` AS `whatever you want for name`,
    `yesterday` AS `whatever you want for yesterday`,
    `today` AS `whatever you want for today`,
    `difference` AS `whatever you want for difference`,
    `quota` AS `whatever you want for quota`,
    `date` AS `whatever you want for date`
FROM {$table} WHERE `active` = 1

Re: alternate field header names in website

Posted: Sun Nov 22, 2009 11:04 pm
by thadson
WOW, so simple.
I have read through like 3 php books and not one of them explained it
Thank you so much

:D

Re: alternate field header names in website

Posted: Mon Nov 23, 2009 12:58 am
by requinix

Code: Select all

for($i=0; $i<$fields_num; $i++)
{
    $field = mysql_fetch_field($res);
    echo "<td>{$field->name}</td>";
}
That bit of code means that the field names from the query are being used as the column headers. By changing the names (using AS) you'll be changing the column headers too.