Insert json_encode of any emoji to mysql - mysql

I am trying to insert emojis into my SQL table. I have some emojis already inserted in my rows from my table, like these one: ⚽(\u26bd), ⭐(\u2b50) and ⛔ (\u26d4).
I have already tried to insert and update my rows from my table with different emojis, but i can't. I have discovered the reason that MySQL has allow me to insert the other 3 emojis and it's because the codification of they only have one \. If i try to insert a different emoji which the ascii codification has more than \, the information in the row will magically disappear, or it will be replaced with ????.
This is my query to update the one row from my table to add an emoji:
UPDATE myusers SET name = "\u26bd William" WHERE id = 8
If i run the query in my table it will insert in the row name \u26bd William, as i want.
But if i try with a different emoji which ascii codification it's like this 🚀(\ud83d\ude80)
UPDATE myusers SET name = "\ud83d\ude80 William" WHERE id = 8
The query in my table it will insert in the row name ud83dude80William, or ????William, or null. So in this time i have lost information in my row running that query
I have already tried to change the charset of my table, but it didn't make a difference

Finally to fix this issue (reffer to Akina answer, thanks very much) we have to add in the query double backslash.
Example:
UPDATE myusers SET name = "\\ud83d\\ude80 William" WHERE id = 8;
SELECT * FROM myusers;

Related

To insert a single quotes in a table using query

I want to insert single quotes with the data in which I am trying to insert it in a mysql table
Example id column
1 data='rose'
data='rose' should be saved under column
My Actual query is UPDATE test SET ItemType ='doctype="\'text'\"'WHERE ITEMINDEX='221'
Thanks.The following code solved my issue
UPDATE test SET ItemType ='doctype=''text''' WHERE ITEMINDEX='221'

mysql insert if not exists without unique index, or unique key but treat unicode and ASCII as different

I need to insert strings (unicode words) from php array into mysql table but I need no duplicate values
In php can't check duplicates because the single words come by exploding text from various sources and some words can be the same as previous inserted
For each word I need also to insert their ASCII version in the same column but only if unicode word is different to ASCII converted words
In mysql I have one table ´words´ with two columns:
´id´ PRIMARY and ´word´ UNIQUE (utf8mb4_general_ci)
$sql = "
INSERT INTO ´words´ (´word´) VALUES ('$word')
ON DUPLICATE KEY UPDATE
SET ´word´ = '$word'
";
$query->execute();
//ex: if $word = "peter" and $word_ascii = "peter" do not insert $word_ascii
//but if $word = "julià" and $word_ascii = "julia" inert also $word_ascii
if($word != $word_ascii){
$sql = "
INSERT INTO ´words´ (´word´) VALUES ('$word_ascii')
ON DUPLICATE KEY UPDATE
SET ´word´ = '$word_ascii'
";
$query->execute();
}
But in this mode when I try to insert $word_ascii = "julia" that overwrite "julià" which I have already inserted before (due to UNIQUE index and ON DUPLICATE KEY UPDATE)
If I quit the UNIQUE index then have a lot of duplicate entries.
I have tried:
INSERT IGNORE (with and without UNIQUE),
REPLACE ... but still the same problem.
I have tried also to adapt IF NOT EXIST from this old answer : How to 'insert if not exists' in MySQL?
INSERT INTO ´words´ (´word´) VALUES ('$word')
WHERE NOT EXISTS (SELECT * FROM ´words´ WHERE ´word´ = '$word' LIMIT 1);
But unsuccessful. I got a syntax error.
Any help are welcome
With utf8mb4_general_ci, "julià" and "julia" are considered equal.
One possible solution is to change the collation for word to be utf8_bin. Then INSERT IGNORE will work as intended, and you will get two rows, one with "julià", one with "julia".
Do you want to have "julià" mapped to "julia"?
But there may be more to your question -- will you be including, say, Chinese names in both Chinese and how they would be spelled with English letters? Collation is not sufficient.

insert statement sql inserting values into a table in mysql with a where clause condition

I have rails application and its using mysql.
I have a piles table with two columns that I care for.
The columns are name_he_il and name_en_us
I don't have a problem doing these
select name_he_il from piles;
select name_en_us from piles;
I need to insert data into the name_he_il column into the piles table where name_en_us = "a specific value"
I tried something like this
insert into piles (name_he_il) values 'לא מאפיין כלל' where name_en_us = "Extremely Uncharacteristic";
I am getting syntax error.
I was googling and I figured the sql should be
insert into table (column 1) values (blah) where conditions;
but its not working.
Basically that hebrew text means extremely uncharacteristic.
You want to use UPDATE ... WHERE
INSERT is for creating new records only.
Do UPDATE and not INSERT:
UPDATE piles SET name_he_il = 'לא מאפיין כלל' WHERE name_en_us = "Extremely Uncharacteristic";
Insert query is to insert new rom into table. If you already have row with value of "name_he_il" column then you need to use update.
UPDATE piles SET name_he_il='new value' WHERE name_he_es = 'something'

Prevent auto increment on MySQL duplicate insert

Using MySQL 5.1.49, I'm trying to implement a tagging system
the problem I have is with a table with two columns: id(autoincrement), tag(unique varchar) (InnoDB)
When using query, INSERT IGNORE INTO tablename SET tag="whatever", the auto increment id value increases even if the insert was ignored.
Normally this wouldn't be a problem, but I expect a lot of possible attempts to insert duplicates for this particular table which means that my next value for id field of a new row will be jumping way too much.
For example I'll end up with a table with say 3 rows but bad id's
1 | test
8 | testtext
678 | testtextt
Also, if I don't do INSERT IGNORE and just do regular INSERT INTO and handle the error, the auto increment field still increases so the next true insert is still a wrong auto increment.
Is there a way to stop auto increment if there's an INSERT duplicate row attempt?
As I understand for MySQL 4.1, this value wouldn't increment, but last thing I want to do is end up either doing a lot of SELECT statements in advance to check if the tags exist, or worse yet, downgrade my MySQL version.
You could modify your INSERT to be something like this:
INSERT INTO tablename (tag)
SELECT $tag
FROM tablename
WHERE NOT EXISTS(
SELECT tag
FROM tablename
WHERE tag = $tag
)
LIMIT 1
Where $tag is the tag (properly quoted or as a placeholder of course) that you want to add if it isn't already there. This approach won't even trigger an INSERT (and the subsequent autoincrement wastage) if the tag is already there. You could probably come up with nicer SQL than that but the above should do the trick.
If your table is properly indexed then the extra SELECT for the existence check will be fast and the database is going to have to perform that check anyway.
This approach won't work for the first tag though. You could seed your tag table with a tag that you think will always end up being used or you could do a separate check for an empty table.
I just found this gem...
http://www.timrosenblatt.com/blog/2008/03/21/insert-where-not-exists/
INSERT INTO [table name] SELECT '[value1]', '[value2]' FROM DUAL
WHERE NOT EXISTS(
SELECT [column1] FROM [same table name]
WHERE [column1]='[value1]'
AND [column2]='[value2]' LIMIT 1
)
If affectedRows = 1 then it inserted; otherwise if affectedRows = 0 there was a duplicate.
The MySQL documentation for v 5.5 says:
"If you use INSERT IGNORE and the row is ignored, the AUTO_INCREMENT counter
is **not** incremented and LAST_INSERT_ID() returns 0,
which reflects that no row was inserted."
Ref: http://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_last-insert-id
Since version 5.1 InnoDB has configurable Auto-Increment Locking. See also http://dev.mysql.com/doc/refman/5.1/en/innodb-auto-increment-handling.html#innodb-auto-inc...
Workaround: use option innodb_autoinc_lock_mode=0 (traditional).
I found mu is too short's answer helpful, but limiting because it doesn't do inserts on an empty table. I found a simple modification did the trick:
INSERT INTO tablename (tag)
SELECT $tag
FROM (select 1) as a #this line is different from the other answer
WHERE NOT EXISTS(
SELECT tag
FROM tablename
WHERE tag = $tag
)
LIMIT 1
Replacing the table in the from clause with a "fake" table (select 1) as a allowed that part to return a record which allowed the insert to take place. I'm running mysql 5.5.37. Thanks mu for getting me most of the way there ....
The accepted answer was useful, however I ran into a problem while using it that basically if your table had no entries it would not work as the select was using the given table, so instead I came up with the following, which will insert even if the table is blank, it also only needs you to insert the table in 2 places and the inserting variables in 1 place, less to get wrong.
INSERT INTO database_name.table_name (a,b,c,d)
SELECT
i.*
FROM
(SELECT
$a AS a,
$b AS b,
$c AS c,
$d AS d
/*variables (properly escaped) to insert*/
) i
LEFT JOIN
database_name.table_name o ON i.a = o.a AND i.b = o.b /*condition to not insert for*/
WHERE
o.a IS NULL
LIMIT 1 /*Not needed as can only ever be one, just being sure*/
Hope you find it useful
You can always add ON DUPLICATE KEY UPDATE Read here (not exactly, but solves your problem it seems).
From the comments, by #ravi
Whether the increment occurs or not depends on the
innodb_autoinc_lock_mode setting. If set to a non-zero value, the
auto-inc counter will increment even if the ON DUPLICATE KEY fires
I had the same problem but didn't want to use innodb_autoinc_lock_mode = 0 since it felt like I was killing a fly with a howitzer.
To resolve this problem I ended up using a temporary table.
create temporary table mytable_temp like mytable;
Then I inserted the values with:
insert into mytable_temp values (null,'valA'),(null,'valB'),(null,'valC');
After that you simply do another insert but use "not in" to ignore duplicates.
insert into mytable (myRow) select mytable_temp.myRow from mytable_temp
where mytable_temp.myRow not in (select myRow from mytable);
I haven't tested this for performance, but it does the job and is easy to read. Granted this was only important because I was working with data that was constantly being updated so I couldn't ignore the gaps.
modified the answer from mu is too short, (simply remove one line)
as i am newbie and i cannot make comment below his answer. Just post it here
the query below works for the first tag
INSERT INTO tablename (tag)
SELECT $tag
WHERE NOT EXISTS(
SELECT tag
FROM tablename
WHERE tag = $tag
)
I just put an extra statement after the insert/update query:
ALTER TABLE table_name AUTO_INCREMENT = 1
And then he automatically picks up the highest prim key id plus 1.

Edit the latest row in the database?

How can I edit the latest row in the database. I only know it's the last one. I don't know its id.
I don't know which language you are working with, in PHP's mySQL functions you can use
mysql_insert_id()
there are similar function in every other mySQL client library I know of.
Also, there is a native mySQL function!
LAST_INSERT_ID() (with no argument)
returns the first automatically
generated value that was set for an
AUTO_INCREMENT column by the most
recently executed INSERT statement to
affect such a column. For example,
after inserting a row that generates
an AUTO_INCREMENT value, you can get
the value like this:
mysql> SELECT LAST_INSERT_ID();
-> 195
Of course, a primary key with AUTO_INCREMENT is required for these functions to work.
For a table with an auto_increment id field:
UPDATE tbl SET col1 = 'val1' WHERE id = MAX(id);
If it's a row that has been inserted in your script (the same script from which you want to update it) and there is an auto_increment column on your table, you can get that auto_increment value, using functions such as those, for PHP :
mysql_insert_id
mysqli_insert_id
PDO::lastInsertId
There should be an equivalent for probably any language you can possibly be using for your application.
If your are trying to do an update from another script than the one in which you did the insert, and still have an auto_increment column, the best way will probably be to update the row that has the biggest value for that column :
update your_table
set your_column = ...
where id = max(id)
Or, in two steps (not sure it'll work in one) :
select max(id) as id from your_table
update your_table set your_column = ... where id = [what you got with thr first query]
You can also use UPDATE table SET ... WHERE id=LAST_INSERT_ID() (supposing the last insert was on the table you want to query).
I would not use TWO steps to find the last insert ID simply because a new record could be added in the mean time.
Depending on your version, you should be able to call $handle->last_id(); or $handle->{mysql_insertid};
Chris