1

I'm using the following code to check if the column exists, and if it doesn't, add it:

mysql_query("select $column from $table") or mysql_query("alter table $table add $column varchar (20)");

But there's no change in the database. Any suggestions why?

P.S. The database is connected.

9
  • 1
    ^ if that's the case, all the more reason to ask why there's no change. Commented May 7, 2013 at 11:51
  • 8
    FOR THE LOVE OF /dev/null ... dont use the PHP mysql legacy api Commented May 7, 2013 at 11:51
  • Actually no, mysql_query returns false on error. Commented May 7, 2013 at 11:53
  • 3
    Using OR in this place is utter nonsense. A query that does not return any records is not a failed query. Commented May 7, 2013 at 12:03
  • 6
    It's surprising how in 1 line of code you managed to commit so many atrocities against programming, common sense and what not. I sincerely hope you're using that code for the purposes of learning / testing / having fun. Commented May 7, 2013 at 12:09

3 Answers 3

6

You can change your SQL to...

//THIS IS BETTER BUT DONT USE THIS
$qry = "ALTER IGNORE TABLE {$table} ADD {$column} VARCHAR(20);"

Instead use PHP PDO or MySQLi with prepared statements. Instead of that legacy horror with concatinated unescaped strings.

MySQLi Solution:

$mysqli = new mysqli($cfg->host, $cfg->user, $cfg->password, $cfg->db);

if ($mysqli->connect_errno) {
    echo 'Connect failed: ', $mysqli->connect_error, '" }';
    exit();
}

if ($stmt = $mysqli->prepare("ALTER IGNORE TABLE ? ADD ? VARCHAR(20);")) {
    $stmt->bind_param("ss", $table, $column);
    $stmt->execute();
    $stmt->close();
}
$mysqli->close();
Sign up to request clarification or add additional context in comments.

5 Comments

Are you sure? Doesn't bind_param make this query like ALTER IGNORE TABLE "tableName" ADD "fieldName" VARCHAR(20);?
Why worry about the case sensitivity of the table-/field-name?
No no, I mean quotes ALTER IGNORE TABLE "tableName" AD... instead of ALTER IGNORE TABLE tableName AD...
I understand the confusion, going to fix it.
IGNORE only applies to keys though... dev.mysql.com/doc/refman/5.1/en/… That said, qisho's solution is the one i'll be upvoting
3
$r=mysql_num_rows(mysql_query("SHOW columns from '".$table."' where field='".$column."'"));
if ($r==0){
    mysql_query("alter table $table add $column varchar (20)");
}

Comments

0

For msqli users

$result = $mysqli->query("SHOW COLUMNS FROM tablename LIKE 'keyword");
$exists = (mysqli_num_rows($result))?TRUE:FALSE;

Comments

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.