简体   繁体   中英

calling a stored procedure from php

I'm calling a stored procedure from php

<?php
include('global/db.php');
$id = 1;
$base = conn();
$query = "CALL get_id(:id,@userid)";
$stmt = $base->prepare($query);
$stmt->bindParam(':id',$id);
$stmt->execute();
print_r($stmt->fetch());
?>

the stored procedure looks like this

BEGIN
SET @userid = (SELECT * FROM user WHERE user.id = id);
SELECT @userid;
END

the procedure parameters

IN id int(10), OUT userid VARCHAR(255) 

Questions:

  • why does my result return nothing?
  • what data type does my output variable @userid need to be?

Your stored procedure has some problems.

Since you have an output userid why this @userid .

Also you are outputting userid , So there is no need to SELECT it

Another thing is, you can't select the entire row into a single variable, for multiple columns you should use multiple output variables.

BEGIN
    SET userid = (SELECT column_name FROM user WHERE user.id = id);
END

Update

$result = $base->query("CALL get_id($id)");  
while($data = $result->fetch_array(MYSQL_ASSOC)){
   echo $data['column_name'];
}

Currently, you are defining a scalar parameter to entire query resultset as noted by asterisk. Consider using INTO clause to pass one query result value into the OUT parameter:

DELIMITER $$
CREATE PROCEDURE get_id (
  IN  id int(10), 
  OUT userid VARCHAR(255))
BEGIN
  SELECT user.id
  INTO userid
  FROM user
  WHERE user.id = id;
END$$
DELIMITER ;

And in PHP, you need to run a second query to return the @userid variable in a fetch command:

try {
    include('global/db.php');
    $id = 1;
    $base = conn();
    $query = "CALL get_id(:id,@userid)";
    $stmt = $base->prepare($query);
    $stmt->bindParam(':id',$id);
    $stmt->execute();

    $result = $base->query("SELECT @userid")->fetchAll();
    if ($result) { print_r($result); }

} catch (PDOException $pe) {
    echo $pe->getMessage()."\n";        
}

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