views:

120

answers:

1

I have two different queries in my php page for the same table, the first one is executed if I have two different values for two columns, but in some case, i can use only the first value, can I do it with the same query or should I use two different queries?

// query 1
"INSERT INTO my_table (column_1, column_2) VALUES ('$value_1', '$value_2')";

// second query, used if $value_2 is null
"INSERT INTO my_table (column_1) VALUES ('$value_1')";

// can I do something like this without use a SELECT for column_2 before the INSERT?
$value_2 = null;
"INSERT INTO my_table (column_1, column_2) VALUES ('$value_1', '$value_2')";
// ======================================= new value === ^   |    ^ === mantain old value because it's null

so can I execute an INSERT statement with new vals without overwrite the old vals with a null value?

+2  A: 

An INSERT will never overwrite an old record (though it could fail if you try to insert a record that breaks a unique key constraint). So you can just use the first query, even if $value_2 is null, and get the same results.

If you want to overwrite records, you will need to use an UPDATE statement. In that case you could overwrite only a single column, if you wanted to. See http://dev.mysql.com/doc/refman/5.0/en/update.html for the UPDATE syntax.

There is also REPLACE to overwrite old rows in the case of unique keys, but it sounds like this is the opposite of what you want to do.

danben
ok thanks, I'll remember the difference between INSERT and UPDATE, cya
Vittorio Vittori