Lamont Peterson wrote:
On Monday 28 January 2008 03:51:28 pm Wade Preston Shearer wrote:
The AS option in an SQL command allows you to rename a field, like this:

select username as user, password as secretcode


Is it possible to rename all of the fields that you pull at once?
Here's what I want to do:

I have a table of fields that are all named with the same prefix. I
want to rename them as they are pulled from the DB with a different
prefix. Is that possible?

MySQL (nor any other RDBMS, AFAIK) does not have any function that will do this for you, but from within PHP, it wouldn't be hard to write a simple loop. Here's an overview (I don't have time right now to write up the code, sorry):

1.  $fields = "DESCRIBE TABLE db.table"
2.  $query = "SELECT ";
3. foreach ($fields as $field) { $query += $field."AS ".(preg_replace ('/^old_prefix_/', 'new_prefix_', $field)).", "; }
4.  Add any other query elements, like a WHERE clause.
5.  Run the $query.

I think that method would be pretty simple to implement and should work with just about any SQL RDBMS.
I've found that it's best to have a function that's not "hidden" such as a db view might be so one year from now if you have to figure out what you did, it's easy to see. Thus, I would go with something like Craig or Lamont suggested.



_______________________________________________

UPHPU mailing list
[email protected]
http://uphpu.org/mailman/listinfo/uphpu
IRC: #uphpu on irc.freenode.net

Reply via email to