简体   繁体   中英

How to get the single return value from mysql stored function in php

I want return the last inserted id using the following function: MySql Stored Function:

CREATE DEFINER=`root`@`localhost` FUNCTION `set_user`( user_id int(11), u_name varchar(50),              
                                                      pass  varchar(128)) RETURNS int(11)
BEGIN
DECLARE newest_id INT(11);

INSERT INTO `test_db`.`users`
(`id`,`user_name`,`password`)
VALUES (user_id, u_name, pass);

SELECT LAST_INSERT_ID() INTO newest_id FROM test_db.users;

RETURN newest_id;
END

And here is the php code:

$sp = "select test_db.set_user(1, 'uname', 'pass123')";

$res = $con->multi_query( $sp );
if( $res ) {
  $results = 0;

    if ($result = $con->store_result()) {
      printf( "<b>Result #%u</b>:<br/>", ++$results );
      while( $row = $result->fetch_assoc() ) {
        echo $row["newest_id"];
      }
      $result->close();

    }

}

the function is successfully inserts the data But php is not getting the single return value. Please help.

You're not assigning the alias newest_id to the result of your SELECT :

$sp = "select test_db.set_user(1, 'uname', 'pass123') AS newest_id";

The variable inside the procedure is not visible outside it, and doesn't become the name of the column returned by the SELECT .

I have checked you function it's all good but need some changes to work perfectly , so check these points:-
1. Add a LIMIT 1 on select statement for LAST_INSERT_ID as LAST_INSERT_ID() return multiple rows with same LAST_INSERT_ID.

DELIMITER $$
CREATE DEFINER=`root`@`localhost` FUNCTION `set_user`( user_id int(11), u_name varchar(50),              
                                                      pass  varchar(128)) RETURNS int(11)
BEGIN
DECLARE newest_id INT(11);
INSERT INTO `test_db`.`users`
(`id`,`user_name`,`password`)
VALUES (user_id, u_name, pass);

SELECT LAST_INSERT_ID() INTO newest_id FROM test_db.users LIMIT 1;

RETURN newest_id;
END $$
DELIMITER ;
  1. Then add the alias "newest_id" in select query in PHP.

    $sp = "select test_db.set_user(1, 'uname', 'pass123') as newest_id"; $res = $con->multi_query( $sp ); if( $res ) { $results = 0; if ($result = $con->store_result()) { printf( "<b>Result #%u</b>:<br/>", ++$results ); while( $row = $result->fetch_assoc() ) { echo $row["newest_id"]; } $result->close(); } }

    I hope it will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM