Gideon
Gideon

Reputation: 1886

Using arrays and loops with SELECT AS syntax in SQL

I am generating a table in HTML from a MySQL database, so that stored data can be displayed on a web page, and ultimately downloaded as a spread sheet.

I have a large set of SQL headers (probably the wrong name for this), that is to say the 'Title' of any given column.

I am using SELECT to get the data from MySQL via PDO:

           $sql ="
             SELECT     
            `sv_20`  AS `Name`,
            `sv_21`  AS `Age`,
            `sv_22`  AS `Height`,
            `sv_23`  AS `Weight`,
            ...
            ...
            `sv_999`  AS `Something`

        FROM 
            database.table";

In PHP I would define two arrays (the database headers and the titles I'd like them to have) and then write a foreach loop saying:

 foreach(array_combine($headers, $titles) as $header => $title)
 {
 echo "`$header`  AS `$title`,";
 }

Which would give me the complete set of calls, is there a way to do this in SQL when querying a database? Thank you

Upvotes: 0

Views: 110

Answers (1)

Karoly Horvath
Karoly Horvath

Reputation: 96266

It's basic string manipulation, instead of echo, you want to append this to the string with $sql .=

You'll have some problems with the extra comma after the last item, it's better to

$sql = array();
foreach(....)
    $sql[] = "`$header`  AS `$title`";

and then do a join(',', $sql);

Upvotes: 1

Related Questions