06-30-2007, 03:11 PM
I am trying to create a new column in a table where the column name will be equal to the value of a variable.
$trendDate = date("F j, Y");
$newCol = "ALTER TABLE trendData ADD $trendDate INT(5)";
However what's happening is that the new column is just being named $trendDate (not the actual value). Is it possible for me to do what I am trying to do? Thanks in advance!
06-30-2007, 03:50 PM
The only way that the posted query could have created a column named $trendDate is if at some point in time you had single-quotes around the query string.
The date(...) function with the format string you are using produces a date like this - June 30, 2007, giving a query like this -
ALTER TABLE trendData ADD June 30, 2007 INT(5)This is not a valid column name identifier and the query is failing with a syntax error.
Please add some error checking and error reporting to your mysql_query(...) statement to get mysql to tell you what is going on -
mysql_query($newCol) or die('The alter query failed: ' . mysql_error()); Of greater concern is that adding columns to your table to apparently identify and hold data for a specific date will result is a poor database design. You should instead have one column for the date and a second column for the data. To INSERT a row, just insert the date/data pair in their respective columns. To SELECT all the data for any date, just specify the date in the WHERE clause in the query.
06-30-2007, 04:23 PM
Unfortunatley, I can't change the design of the database. My major concern is if I can get the new column name to take the value of any variable at all. So, forgetting the time function, could I for instance get the name of the new column to take a variable $variable = "random_string"
Is it possible for me to do this? Thanks!