-1

I want to store date as column name in php.

I tried below code but its giving error.

<?php
    $dbhost = "localhost";
    $dbuser = "id788089_smartcollegeapp";
    $dbpass = "smart123";

    mysql_connect("$dbhost","$dbuser","$dbpass") or die(mysql_error());
    mysql_select_db("id788089_smartcollegeapp");

    $date = date('Y-m-d H:i:s');

    $table = trim($array_not_present_student[0]) . 
             '_' . trim($array_not_present_student[1]) . 
             '_' . trim($array_not_present_student[2]) . 
             '_' . trim($array_not_present_student[3]) . 
             '_' . trim($array_not_present_student[4]);

    $new ="ALTER TABLE " . $table . " ADD " . $date . " VARCHAR(255) NOT NULL";
    mysql_query($new)or die(mysql_error());

?>

Error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '2017-03-26 04:14:51 VARCHAR(255) NOT NULL' at line 1.

7
  • 2
    Obvious answer, you can't have spaces in a column name. Obvious question... why would you want to do this.
    – gview
    Commented Mar 26, 2017 at 4:24
  • actually i sent attendance data from my android and store in mysql with date and time . thank you !
    – iamkdblue
    Commented Mar 26, 2017 at 4:27
  • how to can i remove spaces from this $date variable?
    – iamkdblue
    Commented Mar 26, 2017 at 4:28
  • 2
    You can have spaces in a column name. Regardless, this is a terrible idea. Whatever it is you're trying to do, there's a better solution.
    – shmosel
    Commented Mar 26, 2017 at 4:49
  • 1
    The answer is you make a table that has a column named 'attendance' that is either a DATETIME or a TIMESTAMP. Then you use a query like this: INSERT INTO TABLE (
    – gview
    Commented Mar 26, 2017 at 22:17

1 Answer 1

3

Try below query. It worked in MySQL. Added ` before $date.

$new ="ALTER TABLE ".$table." ADD `".$date."` VARCHAR(255) NOT NULL";
3
  • 1
    Then mark it as accepted. By the way mysql has been deprecated, start learning mysqli and pdo, also creating column name as date is not good idea. Commented Mar 26, 2017 at 5:06
  • again thank you for giving advice so can you give any alternative solutions for date
    – iamkdblue
    Commented Mar 26, 2017 at 5:08
  • @kdblue Use rows instead of columns. That's what they're meant for. @ SachinPATIL Why would you help OP shoot himself in the foot??
    – shmosel
    Commented Mar 26, 2017 at 5:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.