Calling stored procedure from codeigniter

2019-04-30 04:22发布

问题:

I am using codeigniter that has mysqli as db driver, am trying to call a simple stored procedure from my model but get an error. What am i doing wrong

Error Number: 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 'pc()' at line 1

pc()

Filename: C:\hosted\saner.gy\ipa\system\database\DB_driver.php

Line Number: 330

When i run the query call Stored Procedure it runs well but from codeigniter it throws the above error

Stored Procedure

CREATE DEFINER=`root`@`localhost` PROCEDURE `pc`()
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN
    SELECT * FROM tbl_flo
  WHERE name = 'sam';
END

Controller

public function sp()
{
$this->User_model->pc();
}

Model

public function pc()
        {
            $query = $this->db->query("pc()");

            return $query->result();
        }

回答1:

Stored procedures are invoked using the CALL procedure_name(optional_params) query.

You need to edit the query used in your model like this:

public function pc()
    {
        $query = $this->db->query("CALL pc()");
        return $query->result();
    }


回答2:

You are using the following way to call procedure.

$this->db->call_function('pc');

Or you can also use this

$this->db->query("call pc()");


回答3:

Here is dude, This block of code work for me at model

function get_sunmeter_for_initiator($data){
        try {
            $this->db->reconnect();
            $sql = "CALL `get_sunmeter_for_initiator`(?, ?, ?)";
            $result = $this->db->query($sql,$data); // $data included 3 param and binding & query to db
            $this->db->close();


        } catch (Exception $e) {
            echo $e->getMessage();
        }
        return $result;

    }