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.

0

1 Answer 1

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

You have to specify length

Sign up to request clarification or add additional context in comments.

4 Comments

...I feel silly now. Thanks, it worked like a charm.
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
@user2997488 Try adding PDO::PARAM_STR after $column_name.But I`m not sure you can use placeholders for table or column names.stackoverflow.com/questions/13405392/pdo-bindparam-issue
Nop, doesn't work:Fatal error: Call to undefined function name() => name is just a random value taken from ($_POST['<user input>'])

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.