My web application receives an update form for a db record, submitted by the user.
I would like to create an sql which will update all the values to exactly what the user submitted, except those which the user left blank. For those, I want the value to be set to its DB default.
Is there a way to do it?
I'm looking for something like
update my_table set col1=17, col2=DEFAULT, col3='some text'
Please notice that I'm updating an existing row, thus I cannot just live some columns out from the update sql, as they might have had a value before which needs to be erased now.
There is a DEFAULT(col_name) function:
Returns the default value for a table column. An error results if the
column has no default value.
UPDATE my_table SET col1=17, col2=DEFAULT(col2), col3='some text'
Well apparently it's just that simple, exactly as I wrote:
update my_table set col1=17, col2=DEFAULT, col3='some text'
http://dev.mysql.com/doc/refman/5.0/en/update.html
Related
The webhosting I use has enabled StrictMode for the Databases. All my php scripts now stopped working because they report I haven't defined a default value for some columns.
As I have a lot of columns in a lot of tables, is there a way to set all the columns with "default value = none" with "default value = NULL" ?
In this way it won't report me the error anymore.
Of course, If there's another (better) way, I am available for it.
I tried looking on the net, but I couldn't find anything suitable for this case.
you can alter column
ALTER TABLE table_name
MODIFY COLUMN col datatype DEFAULT null
A general approach here which should work for each column causing an error would be to set a default value, and then maybe do an update to backfill records missing a value.
ALTER TABLE yourTable ALTER some_text_column SET DEFAULT 'None';
And here is the update:
UPDATE yourTable SET some_text_column = 'None' WHERE some_text_column IS NULL;
You are not required to do this update, but it might make sense to bring older records missing values in line with what newer records would look like.
I'm creating a user registration form and when I get to confirming the user's email by emailing them, I need some sort of unique string to confirm against.
Instead of generating one in PHP and inserting it into the database, I wanted to try and add a column to my table that would hold a unique value that I could use whenever I needed to confirm something.
What I want to do is set the value to an MD5 of the current timestamp. I tried just doing SELECT MD5(CURRENT_TIMESTAMP) in phpMyAdmin just to see if it would let me and it did so I thought I'd add that to an update condition but it doesn't seem to be letting me.
ALTER TABLE users ADD confirmation VARCHAR(40) DEFAULT NULL ON UPDATE MD5(CURRENT_TIMESTAMP);
The above is what I've tried. I get an error and I don't know how else to do it.
Is there anyway I can do this or something similar? Side question, does the ON UPDATE trigger on a row that just got inserted?
The syntax you are trying to use doesn't exist. It looks like you are thinking of ON UPDATE CURRENT_TIMESTAMP but that is a rather specific command, as per https://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html
Use of DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP is
specific to TIMESTAMP.
So the ON UPDATE clause only works with CURRENT_TIMESTAMP and only on fields of type TIMESTAMP.
If you want to use the MD5 of the current timestamp either set a trigger, or just manually set the value (e.g. UPDATE users SET confirmation=MD5(CURRENT_TIMESTAMP()) WHERE user_id=123).
Bare in mind that the MD5 of the current timestamp is something that could be quite easily guessed / brute forced, so don't rely on it for security.
Use a universal unique identifier for this purpose. It's a 128-bit unique number; it's designed for this kind of thing.
It has a string representation that fits in 36 bytes.
aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
You can generate these things in most programming languages. In MySQL you use the UUID() function to get one. Every time you call UUID(), you're guaranteed to get a new value.
Add a CHAR(36) column to your database, or just use your VARCHAR(40) column.
You can't use data definition language (ALTER TABLE) to declare ON UPDATE except for a native timestamp. You'll need application code to set your UUID values, just like you do for MD5(CURRENT_TIMESTAMP).
Im currently using CodeIgniters active record class to UPDATE a MySQL table. One of the columns is an INT who's default value I've set to NULL and set the NULL field to TRUE. When I INSERT a record and leave that particular field blank in the form, no problem, it's set to NULL. However, when I do an UPDATE with the field blank in the form, MySQL sets the value to 0. Is there a way to have MySQL intepret an UPDATE the same way an INSERT is done i.e. if the form value is blank it sets it to NULL and not 0?
Cheers
Most likely empty string '' is sent to the database thus it is cast to INT field as 0 - check exact SQL query (eg. by enabling profiler: $this->output->enable_profiler(TRUE) in your controller). If that's the case add a snippet to your model that will replace '' with NULL while updating.
Have you run a trace on the database to see exactly what SQL CodeIgniters is sending the database? It sounds like CodeIgniters may be sending the zero to MySQL...
MySQL: In update trigger's body, can I obtain the value of a column that is specified in the where clause of the triggering query if the where clause does not match any rows at all?
I have to do the following, but NOT USING direct query such as ON DUPLICATE KEY UPDATE so on:
If I have:
UPDATE my_table SET idiotism_level=5 WHERE name='Pencho'
... and the where clause match NO ROWS, I'd want to automatically trigger an insertion of a row having name='Pencho' before the update, and then the UPDATE would presumably match, and work properly.
Is it possible ?
This could be make in a RULE in other database systems (PostgreSQL), that does not exists in MySQL. It's a Rule and not a trigger as you should analyse the query and not the result of the query.
But for MySQL you can make pre-query jobs by using MySQL-Proxy. You should be able to alter your update query and build an insert, By running some 'check row exists' extra query from the MySQL-Proxy (I'm not saying this is a nice solution, but if you have no way to make the code to act better you can fix it at this level).
No. An update trigger fires once for each row that gets updated, not once for each update command that's executed. There's no way to make the trigger fire if nothing is updated. You would need to handle this in your application by checking the number of updated rows returned by your query.
If name has a unique index on it you can use REPLACE
REPLACE INTO my_table (idiotism,name) VALUES ( 5,'Pencho');
With the query below, I am trying to overwrite the 10th field in a MySQL table called "login" with the value NEW_VALUE. It's not working. Is the code below the correct method for overwriting existing data in a MySQL table?
Thanks in advance,
John
INSERT INTO login VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'NEW_VALUE', NULL, NULL, NULL)
Just as an addition if anyone is still looking for an actual overwrite and not just an update. If you want to OVERWRITE always, (not update, just overwrite) you can use REPLACE instead of INSERT.
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. See Section 13.2.5, “INSERT Syntax”
http://dev.mysql.com/doc/refman/5.5/en/replace.html
No your code is not correct. You are adding a new row to your table not updating existing values. To update existing values, you want to use an update statement:
Upate a specific record
mysql_query("Update login SET nameOfYourColumn = '$cleanURL' WHERE primaryKey = idOfRowToUpdate")
To update the entire table
mysql_query("Update login SET nameOfYourColumn = '$cleanURL'")
If I've understood your question then the answer is "no". This isn't a mysql specific issue either, it's a generic SQL question. I'd strongly recommend going through an SQL tutorial, the best one I know if is here:
http://philip.greenspun.com/sql/
To answer your question, you should be able to do:
mysql_query("UPDATE login SET foo = '$cleanurl'");
where "foo" is the name of the tenth field.
A few other comments though:
Firstly, don't rely on the position of your fields, always explicitly list the field names. For example, it's better to go
INSERT INTO login (id, name) VALUES (1, 'Fred')
instead of
INSERT INTO login VALUES (1, 'Fred')
Point 2: You have directly embedded the value of $cleanurl into your query. Of course, you have to learn one thing at a time but be aware that this is very dangerous. If $cleanurl contains something like "'); DROP TABLE login;" then you might be in trouble. This is called SQL injection and is the source of constant security problems. Without going into too much detail, you should learn how to use prepared statements.
Point 3: PHP comes with a library called PDO which supports prepared statements. It also provides a common API for interacting with your database so if you find that you need to move from Mysql to another DBMS, PDO will abstract away most of the differences. By using the mysql_query function you lock yourself into using mysql.
You don't have to address all of these issues simultaneously but don't forget about them either, once you get familiar with PHP and SQL come back to the points about PDO and prepared statements.
First off: INSERT adds a new record to a table, UPDATE updates (overwrites) one or more existing records.
Second: UPDATE needs to know the name of the column to update, and which rows to update
UPDATE <tableName>
SET <columnName> = '$cleanurl'
WHERE <some condition to identify which record should be updated>
Thirdly: it's probably worth your while reading a few basic tutorials on MySQL/SQL