View Full Version : Column name in the output of mysql query needs to be changed using php

03-25-2004, 12:26 PM
Dear Friends,

I want the result of a database query needs to be sorted .

I am having a table in which the "ID", "first" "last", "address" , and "position" are the column names . "first " refers to the first name of the employee .

When I sort the result using the following code , the result is getting sorted , but as I have stored the coulumn names as "first" and "last" , the reulting page also contains "last" , "first" which is not user friendly . I want to change the coulmn names of the table using the php code . Its very difficult for me to go and change the names in the database , because everywhere in our application we have referred with "first" , " last"

The code that I have taken from codewalkers.com is :

/* set the allowed order by columns */
$default_sort = 'id';

$allowed_order = array ('id', 'first', 'last', 'address', 'position');
/* if order is not set, or it is not in the allowed
* list, then set it to a default value. Otherwise,
* set it to what was passed in. */
if (!isset ($_GET['order']) ||
!in_array ($_GET['order'], $allowed_order)) {
$order = $default_sort;
} else {
$order = $_GET['order'];
/* connect to db */
mysql_connect ('localhost','root');
mysql_select_db ('mydb');
echo $order;
/* construct and run our query */
$query = "SELECT * FROM employees ORDER BY $order";
$result = mysql_query ($query);
/* make sure data was retrieved */
$numrows = mysql_num_rows($result);
if ($numrows == 0) {
echo "No data to display!";
/* now grab the first row and start the table */
$row = mysql_fetch_assoc ($result);
echo "<TABLE border=1>\n";
echo "<TR>\n";
foreach ($row as $heading=>$dav) {
/* check if the heading is in our allowed_order
* array. If it is, hyperlink it so that we can
* order by this dav */
echo "<TD><b>";
if (in_array ($heading, $allowed_order)) {
echo "<a href=\"{$_SERVER['PHP_SELF']}?order=$heading

} else {
echo $heading;
echo "</b></TD>\n";
}echo "</TR>\n";
/* reset the $result set back to the first row and
* display the data */
mysql_data_seek ($result, 0);
while ($row = mysql_fetch_assoc ($result)) {
echo "<TR>\n";
foreach ($row as $dav) {
echo "<TD>$dav</TD>\n";
echo "</TR>\n";
}echo "</TABLE>\n";

I need the coulmn names to be "EmployeeID", "FirstName", "LastName", "Address", "Position"

Please help me in this .

I welcome all your valuable suggestions


03-25-2004, 05:05 PM
there are many ways to do the replacement , just one of them would be to alter your query so..

$query = "SELECT
ID as EmployeeID,
first as FirstName,
last as LastName,
FROM employees
ORDER BY $order

...again this is only one way , whether its the best for your situation is hard to say