MySQL update if exists else insert throws syntax error - mysql

Trying to update existing records based not on ID but specific usernames with no luck. I wrote the following query but I got a syntax error I can't find.
IF EXISTS (SELECT 1 FROM users WHERE username = 'REMOTEUSER1')
THEN
BEGIN
UPDATE users
SET username = 'REMOTEUSER1', password = 'BJxp98YkVbt4', exp_date = '1650991560', member_id = 1, is_mag = '0', play_token = '', reseller_notes = ''
WHERE username = 'REMOTEUSER1'
END;
ELSE
BEGIN
INSERT INTO users (
username,
password,
exp_date,
member_id,
is_new,
play_token,
reseller_notes
) VALUES (
'REMOTEUSER1',
'BJxp98YkVbt4',
'1650991560',
1,
0,
'',
''
)
END;
END IF;

The IF-ELSE conditional statement construct is supported to be used through FUNCTIONS or STORED PROCEDURES that can't use it like a normal query.
If your username column is UNIQUE index or PRIMARY KEY I would use INSERT ... ON DUPLICATE KEY UPDATE Statemen
INSERT INTO users (
username,
password,
exp_date,
member_id,
is_new,
play_token,
reseller_notes
) VALUES (
'REMOTEUSER1',
'BJxp98YkVbt4',
'1650991560',
1,
0,
'',
''
) ON DUPLICATE KEY UPDATE
password = 'BJxp98YkVbt4',
exp_date = '1650991560',
member_id = 1,
is_mag = '0',
play_token = '',
reseller_notes = '';
sqlfiddle

If is_mag is a bit(1) (boolean), then it's likely the update portion where you set it to '0'
either set the boolean to an integer value of 0, or prefix it with b
i.e.
my_bool = b'0'

Related

How stored procedure output instead of rows count?

My stored procedure always returns 0. I tried unique data and duplicated but the insert is done with success but the return value is always the same #new_identity = 0
CREATE PROCEDURE [dbo].[spAddAuthor]
#Author tyAuthor READONLY,
#new_identity INT = NULL OUTPUT
AS
BEGIN
SET NOCOUNT ON;
-- check if the author exists
IF NOT EXISTS (SELECT Id_Author FROM dbo.Authors
WHERE (dbo.Authors.Username = (SELECT Username FROM #Author)
OR dbo.Authors.phone = (SELECT phone FROM #Author)
OR dbo.Authors.email = (SELECT email FROM #Author)))
BEGIN
INSERT INTO dbo.Authors (Username, sexe, email, phone, address)
SELECT [Username], [sexe], [email], [phone], [address]
FROM #Author
-- output the new row
SELECT #new_identity = ##IDENTITY;
END
ELSE
BEGIN
-- get the author Id if already exists
SELECT #new_identity = (SELECT TOP 1 Id_Author
FROM dbo.Authors
WHERE (dbo.Authors.Username = (SELECT Username FROM #Author)
OR dbo.Authors.phone = (SELECT phone FROM #Author)
OR dbo.Authors.email = (SELECT email FROM #Author)))
END
END
I found that in the declaration of the parameters I put null beside the output and that what caused the problem.
#new_identity INT = NULL OUTPUT
but I don't understand why, I thought the 'null' was like the default value, or when you try to make the parameter optional you add null as default value.
can someone explain, please?

MySQL update or insert for tables without primary key

I know the simple way to perform update or insert is using 'REPLACE' but it needs a primary key, how about in the case of a table without primary key?
I have 5 columns in my table:
remark_id(the auto-increment primary key)
user_id
remark_user_id
remark
last_modified
I wish to check whether the pair of user_id and remark_user_id exists first before updating the remark, else a new row will be created to save the remark with the user_id and remark_user_id.
Here's my code
INSERT INTO `users_remark` (`user_id`, `remark_user_id`, `remark`)
SELECT 1,3 ,'testing123'
FROM dual
WHERE NOT EXISTS
(SELECT *
FROM `users_remark`
WHERE `user_id` = 1
AND `remark_user_id` = 3)
After running the SQL, nothing happens in my Database. No record was added or updated.
[Edited]
Code changes using IF...ELSE... but it comes with some syntax errors on first line
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS (SELECT * FROM users_remark WHERE user_id' at line 1
IF EXISTS (
SELECT * FROM `users_remark`
WHERE `user_id`=1 AND `remark_user_id` = 3
)
THEN UPDATE `users_remark` SET `remark` = 'testing123'
WHERE `user_id`=1 AND `remark_user_id` = 3
ELSE
INSERT INTO `users_remark` SET `remark` = 'testing123', `user_id`=1, `remark_user_id` = 3
Here is the query with both INSERT and UPDATE clauses (T-SQL syntax):
IF [condition here] BEGIN
UPDATE `users_remark`
SET `remark` = 'testing123'
WHERE `user_id`=1
AND `remark_user_id` = 3
END
ELSE BEGIN
INSERT INTO `users_remark` (`user_id`, `remark_user_id`, `remark`)
VALUES (1, 3, 'testing123)
END
EDIT: Same query with MySQL syntax
DECLARE #numrecords INT
SELECT #numrecords = count(*)
FROM `users_remark`
WHERE `user_id` = 1
AND `remark_user_id` = 3
IF #numrecords > 0 THEN
UPDATE `users_remark`
SET `remark` = 'testing123'
WHERE `user_id`=1
AND `remark_user_id` = 3
ELSE
INSERT INTO `users_remark` (`user_id`, `remark_user_id`, `remark`)
VALUES (1, 3, 'testing123)
END IF
Hope this will help you.
I finally try on putting code to php, it works and much easier to understand.
$checkRemark = mysqli_query($GLOBALS['db_conn'], "SELECT * FROM `users_remark` WHERE `user_id`=".$data['uid']." AND `remark_user_id` = ".$data['ruid']);
if (mysqli_num_rows($checkRemark)>0){
$remarkSql = "UPDATE `users_remark`
SET `remark` = '".$data['remark']."'
WHERE `user_id`=".$data['uid']."
AND `remark_user_id` = ".$data['ruid'];
} else {
$remarkSql = "INSERT INTO `users_remark` (`user_id`, `remark_user_id`, `remark`)
VALUES (".$data['uid'].", ".$data['ruid'].", '".$data['remark']."')";
}

Join two table and then search for the match

I have two table named security_questions and login. Columns in login tables are:
Username, Security_QA_ID, Security_Answer, Security_Attempts,Last_Login,Password_Attempts
where security_questions have:
ID, Name
where Security_QA_ID is referenced with ID
CREATE DEFINER=`satish`#`%` PROCEDURE `p_chkAnswer`(
IN sq VARCHAR(75),
IN sa VARCHAR(20) ,
IN uname VARCHAR(15) ,
out msg INT
)
BEGIN
select (COUNT(*) > 0) INTO #result from login join security_questions on Security_QA_ID = ID where User_Name=uname and Name=sq and Security_Answer=sa;
set msg = #result;
if #result = 1 Then
UPDATE login SET Last_Login=now(),Password_Attempts=0 where User_Name=uname;
else
UPDATE login SET Security_Attempts=Security_Attempts+1 where User_Name=uname;
End if;
END
but in every time only else part get executes. thanks in advance
Your code is quite confusing and hard to read (for me at least), I simplified your statement into a single SELECT so that I can check if your select is correct, and it appears to be correct:
CREATE TABLE `login`
( User_Name text,
Security_QA_ID int(11),
Security_Answer text,
Security_Attempts datetime,
Last_Login datetime,
Password_Attempts int(11)
);
CREATE TABLE `security_questions`
(ID int(11),
Name text
);
INSERT INTO login SET
User_name = 'a',
Security_QA_ID = 1,
Security_Answer = 'c',
Security_Attempts = NOW(),
Last_Login = NOW(),
Password_Attempts = 0;
INSERT INTO security_questions SET
ID = 1,
Name = 'b';
And the select
SELECT IF(COUNT(*) > 0, 1, 0) AS Authenticated
from (login)
LEFT join security_questions on Security_QA_ID = ID
where User_Name='a' and Name='b' and Security_Answer='c'
Do you have to use this DEFINER? wouldn't it be easier to write PHP/Perl/etc code to check for Authenticated as being non-zero?

Incorrect query result

I have a query which is not returning correct result:
SELECT t.GroupName AS GroupName, t.ApplicationName AS ApplicationName, t.UserName
FROM UserApplication t
WHERE (#ApplicationName IS NULL OR #ApplicationName = '' OR t.ApplicationName = #ApplicationName) AND
(#UserName IS NULL OR #UserName = '' OR t.UserName= #UserName );
Table structure:
CREATE TABLE userapplication
(`ID` INT,
`ApplicationName` VARCHAR(100),
`GroupName` VARCHAR(100),
`UserName` VARCHAR(100))
When I do not pass any value to the parameter then it showing all rows from the table while if pass any value to the parameter #ApplicationName or #UserName it is giving me same result.
Please help
If you correctly set values of user variables your query will work just fine
SET #ApplicationName = 'App 1';
SET #UserName = '';
SELECT t.GroupName,
t.ApplicationName,
t.UserName
FROM UserApplication t
WHERE (COALESCE(#ApplicationName, '') = ''
OR t.ApplicationName = #ApplicationName)
AND (COALESCE(#UserName, '') = ''
OR t.UserName= #UserName);
It's a little bit more succinct version of your query
Here is SQLFiddle demo

mysql stored function simple login, extract int from set

this is my first mySQL stored-function 'cause i've always managed such things with php.
I want a function that checks if a user can log in my client-area.
I wrote the code above:
DELIMITER $$
CREATE FUNCTION `A05`.`login` (user VARCHAR(64),pass VARCHAR(64)) RETURNS INT
BEGIN
declare num_rows int;
declare id int;
SELECT (#num_rows:=COUNT(*)),(#id:=`Credential_id`) FROM `A05`.`Credentials` where `Credential_UserName` = user;
if num_rows = 0 then
-- user not present
return (-1);
end if;
-- user present, checking password
SELECT (#num_rows:=COUNT(*)),(#id:=`Credential_id`) FROM `A05`.`Credentials` where `Credential_id` = id AND `Credential_PASSWORD` = SHA1(pass);
if num_rows = 0 then
-- user presente, password incorrect
INSERT INTO `a05`.`Events` (
`Event_id` ,
`Event_RegistrationDate` ,
`Event_VariationDate` ,
`Event_State`,
`Event_Notes`,
`Event_SenderId`,
`Event_Type`
)
VALUES (
NULL , NOW(), NOW(), 'wp', NULL, id, 1
);
return (-2);
end if;
-- user present, password correct
UPDATE `A05`.`Credentials` SET `Credential_LastAccess`=NOW() where `Credential_id` = id;
INSERT INTO `a05`.`Events` (
`Event_id` ,
`Event_RegistrationDate` ,
`Event_VariationDate` ,
`Event_State`,
`Event_Notes`,
`Event_SenderId`,
`Event_Type`
)
VALUES (
NULL , NOW(), NOW(), 'ok', NULL, id, 0
);
return id;
END
I think that the syntax should be right except for the last statement return id cause i return a set instead of an integer.
The problem is that when i try to store this function on mysql i get this error:
Error 1415: Not allowed to return a result set from a function
Then i changed the last statement from 'return id' to 'return 0' for testing purpose but i keep getting the same error.
Probably is a newbie error cause it's the very first time for me on sql "advanced" scripting.
Thank you very much in advance!