Page 1 of 1

Variable Column names

Posted: Thu Dec 15, 2005 2:49 pm
by tjbarr63
In this code cbocnty is a selection from a previous checkbox. In my table there are 35 columns that represent years. I can't have a column year with all the variables because the table would be too large. I am trying to use $col to match to the years that the user selected and $cnty_ch in the query to represent the counties that the user selected. This is not working. How can you put variable columns into a select statement?

Code: Select all

$cnty_ch=$_GET['cbocnty'];
$yr_ch=$_GET['cboyear'];
$col = $yr_ch;


$query="select ecnty, major, $col FROM emp_major WHERE ecnty=$cnty_ch;"; 
$result_set = pg_Exec ($conn, $query);
$rows = pg_NumRows($result_set); 
for($i=0;$i<$rows;$i++){
echo "<TD width=200><FONT size=2>" . pg_result($result_set,$i,"major") . "</FONT></TD>"; 
echo "<TD width=200><FONT size=2>" . pg_result($result_set,$i,"ecnty") . "</FONT></TD>"; 
echo "<TD width=200><FONT size=2>" .pg_result($result_set,$i, $yr_ch) . "</Font></TD>"; 
} 
?>
Burrito: Please use

Code: Select all

tags when [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting PHP Code In The Forums[/url][/size]

Posted: Thu Dec 15, 2005 3:11 pm
by Burrito
try using backticks "`" around your column name.

also, why not have the years in a separate table as values instead of column names?

Posted: Fri Dec 16, 2005 9:56 am
by tjbarr63
When you say back tics do you mean double quotes? I tried this and my page goes blank. could you show me an example. The data comes to me in very large tables already set up like this.

Posted: Fri Dec 16, 2005 9:59 am
by Burrito
no I mean backticks as in the tilde key...(right next to the number 1 on most keyboards).

example:

Code: Select all

$query = "insert into `someTable` (`".$_POST['someCol']."`) values ('".$_POST['someVal']."')";

Posted: Fri Dec 16, 2005 11:11 am
by tjbarr63
I still can't get it to work, could you modify my original code?

Posted: Fri Dec 16, 2005 11:14 am
by Burrito

Code: Select all

$query="select `ecnty`, `major`, `$col` FROM `emp_major` WHERE `ecnty`=$cnty_ch;";
if that doesn't work, you probably have some kind of sql error. Since I can't see the pg_Exec() function, I can't say what else might be causing the problem. Just make sure you're echoing out mysql_error() on a sql failure.

Posted: Fri Dec 16, 2005 12:39 pm
by tjbarr63
Thanks but it still isn't working. I am using a postgres database with php 5.

Posted: Fri Dec 16, 2005 12:42 pm
by Burrito
ahh...

unfortunately, I've never used Postgres. maybe that explains the "strange" (to me) function (pg_Exec).

I don't know if the backticks will have any bearing then.

sorry :oops: