Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Jun 2007
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    new column from variable

    Hi,

    I am trying to create a new column in a table where the column name will be equal to the value of a variable.
    PHP Code:
    $trendDate date("F j, Y");

    $newCol "ALTER TABLE trendData ADD $trendDate INT(5)";

    mysql_query($newCol); 
    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!

  • #2
    Senior Coder CFMaBiSmAd's Avatar
    Join Date
    Oct 2006
    Location
    Denver, Colorado USA
    Posts
    3,107
    Thanks
    2
    Thanked 326 Times in 318 Posts
    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 -
    Code:
    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 -
    PHP Code:
    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.
    Last edited by CFMaBiSmAd; 06-30-2007 at 03:54 PM.
    If you are learning PHP, developing PHP code, or debugging PHP code, do yourself a favor and check your web server log for errors and/or turn on full PHP error reporting in php.ini or in a .htaccess file to get PHP to help you.

  • #3
    New to the CF scene
    Join Date
    Jun 2007
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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!
    Last edited by nesurfer87; 06-30-2007 at 04:38 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •