How Can i Insert Value in Mysql if it is Unknown? - mysql

Hello Friend I need Help About Mysql. My Database Look Like This
Table name = users
Rows
id = "7" | YourLastIP = ""
MY Query is:
UPDATE users SET `YourLastIP` = `XX.XX.XX.XX` WHERE `id` = `7`
I want to insert but it also wont work for me please guide me
INSERT INTO Users `YourLastIP` = (`XX.XX.XX.XX`) WHERE `id` = `7`
Please Help me How to Insert A value if table value not known.

You are using backticks which means in MySQL that you're meaning a column name, not text. Use single quotes ' instead.

First, the problem is that you have wrap the value with backtick, which is suppose to be single quote since it is a string literal.
UPDATE users SET `YourLastIP` = 'XX.XX.XX.XX' WHERE `id` = '7'
Second, use INSERT ... ON DUPLICATE KEY UPDATE if you want to UPDATE existing ID or otherwise INSERT if it does not exist.
INSERT INTO users(ID, YourLastIP)
VALUES (7, 'ip_here')
ON DUPLICATE KEY UPDATE YourLastIP = 'ip_here'
INSERT ... ON DUPLICATE KEY UPDATE Syntax
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?

Make the column NULLABLE in definition
Then,
CREATE TABLE PRO(ID INT, YOURLASTIP VARCHAR(15));
INSERT INTO PRO values(4, "xxx.xxx.xxx.xxx");

Related

SQL Error when trying to insert one value into one row for a column

I'm using MySQL 5.7 and for some reason my INSERT statement isn't working as before even though the syntax looks correct. It's error-ing out on the where statement...
SQL:
insert into users(age) values('16') where username='r';
If the row for username r already exists perhaps you are looking to update the age value instead?
Use: update users set age = 16 where username = 'r' instead.
Also, I'm just guessing here, but maybe age holds a numeric value, and if so you can remove the quotes around 16.
That syntax isn't correct. You can't use where like that. Perhaps you want something like:
insert into users (username, age)
values ('r', '16')
http://dev.mysql.com/doc/refman/5.7/en/insert.html
Alternatively if that user already exists, you might be looking for an update statement instead:
update users set age = '16' where username = 'r'
INSERT statements must not contain a WHERE clause. Remove it.
If, in fact what you are trying to do is update an existing row, use an UPDATE statement, not an INSERT statement.
update users set age = '16' where username='r';
If you want to insert new records in your table, you have to write query for inserting data.
SQL INSERT INTO Statement syntax is this:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
In your case, if you don't have the record in your database, your query will look like this:
INSERT INTO users (username, age)
VALUES ('r', '16')
But if you want to update existing records in your table, you have to write query for updating data using the SQL UPDATE Statement.
The syntax for this is:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
To update the record/s, you have to specify clause in WHERE which record should be modified.
To modify age of user/s with username that is equals 'r', this is the query:
UPDATE users SET age = 16 WHERE username = 'r'
but if you want to modify for all users which usernames starts with 'r':
UPDATE users SET age = 16 WHERE username = 'r%'
I hope this explanation will help you to understand better SQL statements for INSERT new and UPDATE existing records.

"INSERT IF NOT EXISTS", ELSE UPDATE certain columns in MySQL

I'm using MySQL Workbench (6.3) and I'm trying to create a stored procedure with a specific "INSERT IF NOT EXSISTS" but I think I don't do it well. By the way, I did read this topic http://bogdan.org.ua/2007/10/18/mysql-insert-if-not-exists-syntax.html and tried both examples, it didn't work. Here is the statement :
CREATE DEFINER=`test`#`localhost` PROCEDURE `onPlayerJoin`(
IN uuid CHAR(36),
IN nickname CHAR(16),
IN firstConnection TIMESTAMP,
IN lastConnection TIMESTAMP
)
BEGIN
INSERT IGNORE INTO `test`.`player` (`playerUuid`, `playerNickname`, `playerFirstConnection`, `playerLastConnection`)
VALUES (uuid, nickname, firstConnection, lastConnection);
UPDATE `test`.`player` SET
`playerNickname` = nickname,
`playerLastConnection` = lastConnection
WHERE `playerUuid` = uuid;
END
IF the PK isn't found, INSERT it. ELSE, UPDATE certain columns. (that I can specified) However, it seems that it updates every column, which I would like to restrict to certain columns. Here is my procedure : http://pastebin.com/NfcdU9Rb !
Optional question : is it injection-safe ?
Use INSERT ... ON DUPLICATE KEY UPDATE Syntax
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
Kindly refer the link for details:
http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html

how to uniquely concatenate a value in mysql for a non key field

I'm using a third party mysql table (ie I can't change any of its properties) and I have a row that has id (key), name and value.
I want to store unique cache keys into a row with the name cacheKeys.. and this is my sql statement
$query = "INSERT INTO ".$tableName." (name, value) VALUES ('CacheKeys', '".$key."') ON
DUPLICATE KEY UPDATE value = CONCAT_WS (',', $tableName.value, '$key')";
I've already implemented my caching algorithm, so that every time someone adds a cache key, I check to see if it already exists (from the CacheKeys row above), if it does I fetch it from cache.. otherwise I store it.
Problem is it seems that the sql write operation takes time, and it often stores duplicate cacheKeys
ie: currencies,defaultCurrencyId,user19,currency1,currency1,currency1,currency1,currency1
So I need to check to see that I'm not adding a duplicate key into the cacheKeys field.. and I need to do that using SQL (using php, ie regex etc would just be waaaay to expensive).
Try this::
INSERT INTO tb (firstname, lastname) VALUES ('Jack', 'Doe') IF NOT
EXISTS ( SELECT * FROM tb WHERE firstname='Jack' AND lastname='Doe' );

Is there a way to use ON DUPLICATE KEY to Update all that I wanted to insert?

I know that you can use ON DUPLICATE KEY UPDATE to update a certain value if there is a record for that key already,
I can do this:
INSERT INTO `tableName` (`a`,`b`,`c`) VALUES (1, 2, 3)
ON DUPLICATE KEY UPDATE `a`=1, `b`=2, `c`=3
But how can I do this without having to write out the columns and values twice?
Unfortunately not.
You can get half-way there by not having to repeat the value:
INSERT INTO `tableName` (`a`,`b`,`c`) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE `a`=VALUES(`a`), `b`=VALUES(`b`), `c`=VALUES(`c`);
But you still have to list the columns.
use REPLACE INTO
The meaning of REPLACE INTO is that IF the new record presents new key values, then it will be inserted as anew record.
IF the new record has key values that match a pre-existing record,then the key violation will be ignored and the new record will replace the pre-existing record.
If it is useful, I made a query to avoid writing by hand the last part of the "on duplicate" query, for versions >= 5.0:
SELECT GROUP_CONCAT( CONCAT(COLUMN_NAME,"=values(", COLUMN_NAME,")") SEPARATOR ", ") FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'database_name' AND TABLE_NAME = 'table_name';
and its output is this:
a=values(a), b=values(b), c=values(c), d=values(d)
on a table that has columns a,b,c and d, so you can append to the first part of the query:
INSERT INTO `tableName` (`a`,`b`,`c`, `d`) VALUES (1,2,3,4) ON DUPLICATE KEY UPDATE a=values(a), b=values(b), c=values(c), d=values(d)
UPDATE:
For a very long list of columns you may see a truncated output, you may use this statement before the query above (thanks Uncle iroh):
SET SESSION group_concat_max_len = 1000000;
per #BhendiGawaar's comment on #Lightness Races in Orbit's answer, here is the MySQL 8.019+ version:
INSERT INTO t1 (a,b,c) VALUES (1,2,3),(4,5,6) AS new
ON DUPLICATE KEY UPDATE c = new.a+new.b;
OR
INSERT INTO t1 (a,b,c) VALUES (1,2,3),(4,5,6) AS new(m,n,p)
ON DUPLICATE KEY UPDATE c = m+n;
Works with set as well:
INSERT INTO t1 SET a=1,b=2,c=3 AS new
ON DUPLICATE KEY UPDATE c = new.a+new.b;
INSERT INTO t1 SET a=1,b=2,c=3 AS new(m,n,p)
ON DUPLICATE KEY UPDATE c = m+n;
Copied directly from MySQL Docs
The deprecation warning about the use of VALUES:
The use of VALUES() to refer to the new row and columns is deprecated beginning with MySQL 8.0.20, and is subject to removal in a future version of MySQL. Instead, use row and column aliases, as described in the next few paragraphs of this section.
i know this is an old question, and this is a somewhat unconventional answer, but i ran into the same thing and was having issues with setting the group_concat_max_len property mentioned in another answer and was always getting a truncated result. Another option that I ultimately went with when writing a long script was to use this formula in excel:
=SUBSTITUTE(TRIM(A1), ",", "") & " = VALUES(" & SUBSTITUTE(TRIM(A1), ",", "") & "),"
where A1 is the cell you copy the field name into. To do this quickly, I'd right click the table and copy the select statement to the clipboard, which gives you all the colum names, the formula removes the commas.
Hope this helps someone!

Access Auto-Increment Value During INSERT INTO Statement

I am currently using MySQL. I have a table that has an auto_increment 'id' field, and an 'imgname' field containing a string that is the file name of an image.
I need to generate the 'imgname' value using the auto_increment value that is create by an INSERT INTO statement. The problem is, I don't know this value until I can use mysql_insert_id, AFTER the insert query has run. I would like to know if it's possible to access this value DURING the insert query somehow and then use it to generate my string in the query statement.
Thanks in advance.
I would keep the id and imgname independent of each other and combine the two on SELECT when needed. If the need is frequent enough, create a view.
Have a look at LAST_INSERT_ID() function. If performance is not an issue, INSERT regularly, and then UPDATE using LAST_INSERT_ID(), like:
UPDATE table SET name = CONCAT(name, "-", LAST_INSERT_ID()) WHERE id = LAST_INSERT_ID();