How to know if insert query succeeded in stored proceedure? - mysql

I am writing a stored procedure to create a player:
CREATE PROCEDURE `create_player` (
firstName TEXT CHARACTER SET utf8,
lastName TEXT CHARACTER SET utf8,
username TEXT CHARACTER SET utf8,
password TEXT CHARACTER SET utf8,
email TEXT CHARACTER SET utf8,
gender ENUM('m','f'),
avatar INTEGER,
OUT result INTEGER)
BEGIN
DECLARE insertVal INTEGER DEFAULT 0;
INSERT INTO `Players`
(`PlayerFirstName`,
`PlayerLastName`,
`PlayerName`,
`PlayerPassword`,
`PlayerEmail`,
`PlayerGender`,
`PlayerAvatar`,
`PlayerJoinDate`) VALUES (
firstName,lastName,username,player_hash_password(password),email,gender,avatar,NOW());
END
Say I wanted to let the user know if this insert succeeded or not, how can I find out if it succeeded or not (number of rows affected). I tried to set an integer variable = to the insert statement but that did not work.
What is the typical way of error checking for stored procedures?

As per MySQL documentation on ROW_COUNT(),
ROW_COUNT() returns the number of rows changed, deleted, or inserted by the last statement if it was an UPDATE, DELETE, or INSERT. For other statements, the value may not be meaningful
After insert statement you can read row_count() into OUT parameter result. Use the same result value in the calling program to let the user know the number of rows affected.
Change your procedure as follows:
DROP PROCEDURE IF EXISTS `create_player`;
delimiter //
CREATE PROCEDURE `create_player` (
firstName TEXT CHARACTER SET utf8,
lastName TEXT CHARACTER SET utf8,
username TEXT CHARACTER SET utf8,
password TEXT CHARACTER SET utf8,
email TEXT CHARACTER SET utf8,
gender ENUM('m','f'),
avatar INTEGER,
OUT result INTEGER )
BEGIN
DECLARE insertVal INTEGER DEFAULT 0;
INSERT INTO `Players`(
`PlayerFirstName`,
`PlayerLastName`,
`PlayerName`,
`PlayerPassword`,
`PlayerEmail`,
`PlayerGender`,
`PlayerAvatar`,
`PlayerJoinDate`)
VALUES (
firstName, lastName, username,
player_hash_password( password ),
email, gender, avatar, NOW() );
SELECT ROW_COUNT() INTO result;
END;
//
delimiter ;

When you insert data through ExecuteNonQuery() method. This method returns number of rows affected in database as integer.
For Example.
int i=0;
i= cmd.ExecuteNonQuery();
if( i >0)
{
msg ="Inserted Successfully";
}
else
msg="Not Inserted";

using php code would help you
<?php
include("connect.php");//..your db connection file
$result = mysql_query("SELECT * FROM Players");
if (mysql_num_rows($result)){
echo "Data entered successfully";
}
else
{echo "failed";}
?>

Related

Why I received "null" even if the table contains a specific value for that column? [duplicate]

I have just started to create a stored function this is my first time so I am having a few problems. Currently I call the function using SELECT test(); (test is the function name for now). I want to send a number to the function (username ID) and have the username returned.
I have this working by using SELECT test(1); 1 is the ID of a user in the table. This seems to work as the username is returned, but if I type in any number the same username is returned also.
BEGIN
DECLARE new_username VARCHAR(90);
SELECT `username` INTO new_username FROM `users` WHERE `ID` = ID;
return new_username;
END
I have set the paramter as ID int .
Am I right in thinking that the keyword INTO will put the value of the username into the variable new_username ? If I run it without the INTO I get the error:
Not allowed to return a result set from a function
Have I made any obvious mistakes in this, I hope I havent done it totally wrong. Thanks for any advice :).
Edit : I just added a few more rows into my table , I now get the error:
Result consisted of more than one row
Full sql version:
CREATE DEFINER=`elliotts`#`%` FUNCTION `test`(ID int)
RETURNS varchar(32) CHARSET latin1
BEGIN
DECLARE new_username VARCHAR(32);
SELECT `username`
INTO new_username
FROM `users`
WHERE `ID` = ID;
return new_username;
END
Use:
DROP FUNCTION IF EXISTS `example`.`test` $$
CREATE FUNCTION `example`.`test` (param INT) RETURNS VARCHAR(32)
BEGIN
DECLARE new_username VARCHAR(32);
SELECT `username`
INTO new_username
FROM `users`
WHERE `ID` = param;
RETURN COALESCE(new_username, 'Username not found');
END $$
Mind that the VARCHAR length of the RETURN value matches the variable, which should match the column length you want to return.

MySQL: Problems with procedure parameters

It seems something is wrong with my procedure. When I execute it, it should create an entry, directly modify a column and then return the id of it.
But nothing is created and it also returns nothing (not even an error is shown)
When I use hard coded values instead of using the parameters, the entry is created, but not edited and the ID is still not returned.
Could you guys have a look over it? This is the whole procedure result using the export function of phpMyAdmin:
CREATE DEFINER=`dbuser`#`localhost` PROCEDURE `createRecruitment`(IN `p_user_id` INT(11), IN `p_platform` ENUM('uplay','steam','ps4','xb1') CHARSET utf8, IN `p_activity` ENUM('pve','pvp') CHARSET utf8, IN `p_description` TEXT CHARSET utf8)
MODIFIES SQL DATA
DETERMINISTIC
SQL SECURITY INVOKER
BEGIN
DECLARE v_id INT(11);
INSERT INTO
recruitments (
user_id,
creationDate,
platform_id,
activity,
description
)
SELECT
p_user_id,
CURRENT_TIMESTAMP,
platforms.id,
p_activity,
p_description
FROM
platforms
WHERE
platforms.platform = p_platform;
SET v_id = LAST_INSERTED_ID();
UPDATE
recruitments
SET
lastActivity = creationDate
WHERE
id = v_id;
SELECT v_id;
END
EDIT
It seems the main problem is the "p_platform" parameter. I wanted to limit the input to the given ENUM but it seems the WHERE platforms.platform = p_platform doesn't work proper with this.
Use the below SP. I have use OUT v_id field and assign the value
CREATE DEFINER=`dbuser`#`localhost` PROCEDURE `createRecruitment`(IN `p_user_id` INT(11), IN `p_platform` ENUM('uplay','steam','ps4','xb1') CHARSET utf8, IN `p_activity` ENUM('pve','pvp') CHARSET utf8, IN `p_description` TEXT CHARSET utf8, OUT `v_id` INT(11))
MODIFIES SQL DATA
DETERMINISTIC
SQL SECURITY INVOKER
BEGIN
INSERT INTO
recruitments (
user_id,
creationDate,
platform_id,
activity,
description
)
SELECT
p_user_id,
CURRENT_TIMESTAMP,
platforms.id,
p_activity,
p_description
FROM
platforms
WHERE
platforms.platform = p_platform;
SET v_id = LAST_INSERTED_ID();
UPDATE
recruitments
SET
lastActivity = creationDate
WHERE
id = v_id;
END

Updating a table in my trigger fails

I am trying to update a table using an after insert trigger using this code
SET #OLDTMP_SQL_MODE=##SQL_MODE, SQL_MODE='STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
DELIMITER //
CREATE TRIGGER `le_log_trigger` AFTER INSERT ON `messagelog` FOR EACH ROW BEGIN
declare last_inserted_number VARCHAR(100) DEFAULT '0800100200';
declare last_inserted_code VARCHAR(100) DEFAULT 'Lorem Ipsum';
declare current_dataset VARCHAR(100) DEFAULT 'Lorem Ipsum';
set last_inserted_number = NEW.messagefrom;
set last_inserted_code = NEW.statuscode;
set current_dataset = (select task_name from running_tasks limit 1);
if(last_inserted_code = 201) then
update current_dataset set the_status = 'online' where device_number = last_inserted_number;
end if;
END//
DELIMITER ;
My database is called logan and i get this error when the trigger runs
/* SQL Error (1146): Table 'logan.current_dataset' doesn't exist */
Why is current_dataset not being treated as a variable?.
Because you're trying to do an UPDATE query. MySQL expects to see a table name where you've got your variable, so it won't go "oh, hey, this was declared as a variable earlier". It'll just assume right away that it's supposed to be a literal table name, and look for that table... and since it can't be found (because it doesn't exist), you get that error.
If you DID by chance have a table where a field name did co-incide with a variable name, eg.
table x (foo int, bar int);
set bar='baz';
and did
UPDATE x SET foo=bar
then you've got a problem. Which bar should be used? Are you referring the variable, or to the field? That's why there's #:
UPDATE x SET foo=bar ; // use "bar" field in the table
UPDATE x SET foo=#bar; // use variable "bar" value.
And note that you couldn't use the variable as a table name, e.g.
SET x = 'tablename';
UPDATE #x SET ...
is just a flat-out syntax error. You'd have to build a query string inside your sproc, and then prepare/execute it.

Select into not working for stored proceedure

I'm working on a stored procedure to log in users and I need to return the player id. The provided name and password are correct when I test it, result returns 1 but playerID stays NULL
`player_login` (
username TEXT CHARACTER SET utf8,
txtPassword TEXT CHARACTER SET utf8,
OUT playerID INTEGER,
OUT result INTEGER
)
BEGIN
DECLARE password TEXT DEFAULT player_hash_password(txtPassword);
DECLARE num INTEGER DEFAULT 0;
SELECT PlayerID INTO playerID
FROM players
WHERE (LOWER(players.PlayerName)=LOWER(username) OR LOWER(players.PlayerEmail)=LOWER(username))
AND players.PlayerPassword = password
LIMIT 1;
...
Why is the PlayerID not selected into playerID? PlayerID is a not null auto increment integer.
Your parameter matches the column name, a perennial problem with MySQL stored procedures. Use a prefix for the parameters, something like:
`player_login` (
p_username TEXT CHARACTER SET utf8,
p_txtPassword TEXT CHARACTER SET utf8,
OUT p_playerID INTEGER,
OUT p_result INTEGER
)
BEGIN
DECLARE p_password TEXT DEFAULT player_hash_password(p_txtPassword);
DECLARE num INTEGER DEFAULT 0;
SELECT p_PlayerID = playerID
FROM players p
WHERE (LOWER(p.PlayerName)=LOWER(p_username) OR LOWER(p.PlayerEmail)=LOWER(p_username))
AND p.PlayerPassword = p_password
LIMIT 1;
.

Get the Unique ID for the Last Inserted Row

I want to get the Unique ID for the Last Inserted Row inside stored procedure, I make like this
DELIMITER //
CREATE PROCEDURE addNewUsers(IN userName varchar(128),IN password varchar(128), IN addedBy INT)
BEGIN
DECLARE id int default 0;
id = mysqli_insert_id (insert into `system_users`( `username`,`password`) values (userName ,md5(password)) );
IF id <> 0 THEN
insert into `user_profile`( `full_name`,`Date_time_ added`,`added_by`) values (userName ,CURRENT_TIMESTAMP(),addedBy ) where `user_id`=id ;
END IF
END //
DELIMITER ;
This error occur
#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 '= mysqli_insert_id (insert into `system_users`( `username`,`password`) values (' at line 7
I doubt it's from mysqli_insert_id , what should I do ?
Your mysqli_insert_id is the problem, you're writing a MySQL stored procedure, not PHP. You want to use the last_insert_id() function:
LAST_INSERT_ID() (with no argument) returns a BIGINT (64-bit) value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement.
You also need to fix your assignment syntax. Something more like this:
DELIMITER //
CREATE PROCEDURE addNewUsers(IN userName varchar(128),IN password varchar(128), IN addedBy INT)
BEGIN
DECLARE id int default 0;
insert into `system_users`( `username`,`password`) values (userName ,md5(password));
set id = last_insert_id();
if id <> 0 then
-- ...