3

So far I've got this code:

$column_name = strtolower($_POST['<user input>']);
if(!preg_match('/[^A-Za-z0-9.#\\-$]/', $column_name)){
    if(!empty($column_name)){
    $st = $db_pdo->prepare("DESCRIBE <table name>");
    $st->execute();
    $st = $st->fetchAll(PDO::FETCH_COLUMN);
    $compare = $st;

        foreach($compare as $key){
            if($key === $column_name){
                die('Project name already exists. Please select a different name.');
            }
        }

    $st = $db_pdo->prepare("ALTER TABLE emails ADD <column name> varchar");
    $st->execute();  

  } else { echo 'Project name is empty.';}     
} else { echo 'Project name can only contain letters and numbers.';}

A brief overview is:

Check for invalid characters in column name. Check if column name is not empty via a user input. If table already exists, kill the page.

I'm very new to PHP and MySQL and I'm really sorry if these seem like basic questions.

What I want to do is insert a new column into a table with the type varchar length 60. That's it, no other attribute required.

I can't seem to find the appropriate explanation on how to do this with Google so I'm hoping for some pseudo-code with a bit of explanation.

So far I've got this:

$st = $db_pdo->prepare("ALTER TABLE emails ADD <column name> varchar");
$st->execute();

And don't know how to proceed from this.

Thank you.

Andrei P.
  • 302
  • 3
  • 9

1 Answers1

3
ALTER TABLE emails ADD <column name> varchar(60)

You have to specify length

Mihai
  • 26,325
  • 7
  • 66
  • 81
  • ...I feel silly now. Thanks, it worked like a charm. – Andrei P. Nov 15 '13 at 20:37
  • Follow up question. I've got this code now: $st = $db_pdo->prepare("ALTER TABLE email ADD COLUMN :column_name varchar(60)"); $st->bindParam(':column_name', $column_name); $st->execute(); But it fails to create a new column. What am I missing here – Andrei P. Nov 15 '13 at 20:50
  • @user2997488 Try adding PDO::PARAM_STR after $column_name.But I`m not sure you can use placeholders for table or column names.http://stackoverflow.com/questions/13405392/pdo-bindparam-issue – Mihai Nov 15 '13 at 20:55
  • Nop, doesn't work:Fatal error: Call to undefined function name() => name is just a random value taken from ($_POST['']) – Andrei P. Nov 15 '13 at 21:28