在 codeigniter 中处理存储过程输出参数
Posted
技术标签:
【中文标题】在 codeigniter 中处理存储过程输出参数【英文标题】:Handle stored procedure output parameter in codeigniter 【发布时间】:2013-01-11 18:47:47 【问题描述】:我在 mysql 中有一个带有输出参数的存储过程,我需要将结果发送到我使用 codeigniter 的 php 中
注册模式
public function registerUser($data)
$sql = "call register_new_user('" . $data['uemail'] . "','" . $data['fname'] . "','".$data['lname'] . "','" . $data['pword']."',
'" . $data['states'] . "',".$data['chargifyId'].");";
if ($query = $this->db->query($sql))
return $this->db->query("Select @last_id");
else
return false;
这是存储过程
CREATE DEFINER=`root`@`localhost` PROCEDURE `register_new_user`(IN `uemail` VARCHAR(100), IN `fname` VARCHAR(45),
IN `lname` VARCHAR(45), IN `pword` VARCHAR(100), IN `states` VARCHAR(20), IN `chargifyid` INT, OUT `last_id` INT)
NO SQL
BEGIN
if not exists (SELECT * from gi_user where
(gi_user_email = uemail)) THEN
INSERT INTO gi_user(gi_user_email, gi_user_fname,
gi_user_lname, gi_user_password,gi_user_status,
gi_account_id, chargifyId)
VALUES (uemail,fname,lname,pword,states,1,chargifyid);
SET last_id = LAST_INSERT_ID( ) ;
END IF;
END
【问题讨论】:
请向我们展示您的代码 感谢您的回复,我已经添加了模型和程序 第二个查询没有用,尝试从第一个查询中获取行 $query->row() -- 使用 print_r 或 var_dump 打印出结果并进行测试。 【参考方案1】:使用 CodeIgniter 事务
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
$this->db->trans_complete();
示例:
$SQL = "call UPDATE("
. $ID.","
. $this->db->escape($data["NAME"])."," // input
. $this->db->escape($data["DESCRIPTION"])."," // input
. " @out1" ."," // output
. " @out2" //output
.");";
$this->db->trans_start();
$this->db->query($SQL); // not need to get output
$query = $this->db->query("SELECT @out1 as row_1, @out2 as row_2");
$this->db->trans_complete();
$result = array();
if($query->num_rows() > 0)
$result = $query->result_array();
print_r($result);
【讨论】:
【参考方案2】:$out='';
$query ="begin register_new_user('" . $email . "','" .$name. "','".$lname ."','". $pword."','" . $states . "',:out); end;";
$stmt = oci_parse($this->db->conn_id, $query );
oci_bind_by_name($stmt, ":out", $out,300);
oci_execute($stmt);
echo $out;
它对我有用。
【讨论】:
【参考方案3】:工作示例!
--> SP
CREATE PROCEDURE calculateStock
(IN itemId INT(10), OUT stock INT(10))
BEGIN
DECLARE purchased INT(10);
DECLARE sold INT(10);
SET purchased = (SELECT SUM(purchase_rows.qty) AS purchased FROM purchase_rows WHERE template_id = item_id);
SET sold = (SELECT SUM(sale_rows.qty) AS sold FROM sale_rows WHERE template_id = item_id);
SET stock = purchased - sold;
SELECT stock;
END
--> 型号
public function getStock($item_id)
$query = "CALL calculateStock(?, @stock);";
$parameters = array($item_id);
$result = $this->db->query($query, $parameters);
mysqli_next_result($this->db->conn_id); //Important Line
return $result->row()->stock;
【讨论】:
以上是关于在 codeigniter 中处理存储过程输出参数的主要内容,如果未能解决你的问题,请参考以下文章