Forcing a field in a MySQL table to be lower-case - mysql

I have the field below in a MySQL table. How can I force it to be in lower-case letters only?
`username` varchar(30) NOT NULL,

In the database use the MySQL LOWER() function around the inserts and/or the retrieval. You could also consider just doing it on the application side (meaning you still store the original...
Example
INSERT INTO mytable (username) VALUES(LOWER('TestUser'))
SELECT LOWER(username) FROM mytable

You could use an 'before insert' trigger on the field you want to lowercased.
More infos here : MySQL Trigger
(possible duplicate from here : mySQL phpmyadmin - lowercase data by default)

Rather then implementing it at application level you could write a database trigger that would change the content of the insert/update to lowercase as and when the insert/update happens, independent of the application.

Related

create autoincrement in MySQL with pre text

I have trouble for my project using mysql, i want to create Auto Increment in view table, i create sintax like this one:
SELECT
concat(#AI:= #AI + 1,`code`)
FROM
`TEST TABLE`, (SELECT #AI:=0) as `AI`
Why if i add syntax in first line like this one:
CREATE VIEW `TEST VIEW` as
I have some error :
How fix it, or other method for this?. thanks for advance!
If you were using Oracle, you would use an object called a sequence for this purpose. But, who has the money for Oracle licenses?
If you need a series of numbers and you're using the MariaDB fork, you can do
SELECT seq FROM seq_0_to_99
or some such use of the SEQUENCE engine.
If you need persistent sequence numbers in MySQL, here's a workaround. It's a kludge: If you create the following table:
CREATE TABLE sequence ( /*MySQL*/
sequence_id BIGINT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`sequence_id`)
)
Then issue these three queries one after the other:
INSERT INTO sequence () VALUES (); /*MySQL*/
DELETE FROM sequence WHERE sequence_id < LAST_INSERT_ID();
SELECT LAST_INSERT_ID() AS sequence;
The third query is guaranteed to return a unique sequence number. This guarantee holds even if you have dozens of different client programs connected to your database. (The DELETE query merely keeps this otherwise pointless table from taking up too much space.)
The error message you received makes it clear that you can't use a session variable in a view.
https://dev.mysql.com/doc/refman/5.7/en/create-view.html says:
A view definition is subject to the following restrictions:
The SELECT statement cannot refer to system variables or user-defined variables.
You can't create a view for your query. You'll have to execute the query directly. The only other suggestion I can make is to develop a stored procedure for the query.
It sounds like you want to create a row number for a query result, not an auto-increment column to store in the table.
MySQL 8.0.2 has added the window function ROW_NUMBER(), but 8.0 is still under development as we're writing this. Perhaps in 2018 it will be finished and released as GA.

MySQL MD5(CURRENT_TIMESTAMP) On Update

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).

How to create Trigger to prevent inserting the duplicate row in MYSQL 5.0.27?

This question follows up the following previous question.
is it possible to make a field in Mysql table to to have length max=700, to be unicode (3 bytes) and to be unique?
I have a table MyText which have ID column, text column & many other columns
Id - text - type ..& other fileds
1 - this is my text
2 - xxxx
I want the text column support unicode with max length can hold 700 Unicode characters. I can't set Unique (text) because MYSQL only supports 765 bytes max length for unique column while Unicode takes 3 bytes so I need 2100 bytes (700*3) unique column.
So, the solution is to crate a trigger that prevents the user to insert the duplicate. For example, if user inserts "THIS is My Text" (We won't care case sensitive) into MyText table, then Mysql will abort completely ALL Queries that contain that Inserting Statement and will generate an SQLException to prevent the system to do other query.
Ok, suppose you have to run a series of sql statements in your Java code
insert into MyText('THIS is My Text',1);
insert into OtherTable ('some text');
update othetTable...
Then when the system doing the insert into MyText('THIS is My Text',1);, it should stop doing other queries below it.
Also, some people suggests to do the prefix index to help Nysql to do the select quicker, but I am not sure it is too necessary since I got ID colum which was indexed.
Note: MYSQL 5.027 is 2006 version which is pretty old, but I love it
SO how to create trigger that meets my requirement or how to fix my problem?
I would recommend not using a trigger for this because of performance reasons.
Instead, create an additional column to store an MD5 or SHA1 hash of your value, and make that column unique using a constraint.
As per the above links, both hashing functions exist in your version of MySQL. Alternatively, if it's easier to integrate this in your Java code, you could do the hashing in Java using the MessageDigest class.
The part in your question where you indicate that no further queries should be executed if the insert statement fails because of a duplicate, is best handled using transactions. These are also supported in Java using plain JDBC or most ORM frameworks.

Is there a way to know how many session that open a particular table

I'm trying to generate unique id using php for a table ex: 2013-10-24-01 (yyyy-mm-dd-last_index_plus_1).
The problem is, if there are two session simultaneous open the php
which is access a same table, the generate unique id will be same on them.
I come up with idea that determined the number of session accessing that table
and then plus the last_index by that number,
but i don't know how to accomplished it with mysql.
Is it possible or not?
Thanks
As noted in the comment I am not sure why you want PHP to actually do this, and why the auto_increment is not good enough, but if you need a unique ID you can do the following:
Make sure to add a unique key on the column you are inserting into - if something goes wrong your database will make sure you won't get the two identical keys. In theory you could try until the query succeeds from PHP
You can use the "select for update" (http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html) when selecting the last known sequence to make sure that another process will not try to read before you have inserted it.
The above is possible to do in mysql using a trigger, as you did not provide any structure, the below is just an example of how it could look. It uses a sequence-table for selecting the last id, and the mysql date_format function to format the inserted date.
delimiter |
create trigger `trigger_name`
before insert on `table_name`
for each row begin
set new.last_id = concat(date_format(now(), '%y-%m-%d'), '-', (select max(id) from `sequence_table` for update));
end|
delimiter ;

Overwriting data in a MySQL table

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