Calling stored procedure from codeigniter - codeigniter

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();
}

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();
}

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;
}

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()");

Related

Eloquent Relationship Multiple Connection

I have a multi-connection application. Model Department is on a different connection from model CutOff.
I have a relationship in my CutOff that looks like this:
public function department()
{
$department = new Department();
$database = $department->getConnection()->getDatabaseName();
return $this->belongsTo('App\Department', 'department_id', "$database.department.id");
}
So I try to call it like this from my view ...
$cut_off->department->name;
I get this error:
ErrorException (E_ERROR)
SQLSTATE[42000]: Syntax error or access violation: 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 '.id = ? limit
1' at line 1 (SQL: select * from departments where
departments.uni_main.department.id = 2 limit 1) (View:
C:\wamp\www\university\resources\views\utme\dashboard\cut_off\index.blade.php)
Please how do I get around this?
Set protected $connection = 'the_other_db'; on the Department model which matches what is configured in database.php
Then I can just use
public function department()
{
return $this->belongsTo('App\Department', 'department_id');
}

Inserting a variable in sql through laravel

I am trying to insert data into sql in laravel 5
My Code:
$a1=Input::get('username');
$a2=Input::get('reg_no');
DB::insert("INSERT INTO ngosignup VALUES($a1,$a2)");
But I am getting SQL error:
SQLSTATE[42000]: Syntax error or access violation: 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
'#gmial.com,a,a,a,a,9,a,9814937684,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,N'
at line 1 (SQL: INSERT INTO
ngosignup(name,email,pass,confirmpass,address,city,pin,state,mobile,registration,secretary,dest,firstmember,mobile1,secondmember,mobile2,thirdmember,mobile3,objective,dev1,place1,obj1,dev2,place2,obj2,dev3,place3,obj3)
VALUES(a,amit#gmial.com,a,a,a,a,9,a,9814937684,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL))
PLEASE HELP.
Try Eloquent way.. for example of using your db.. Make a Model for ngosignup table and include it on controller
public function create(\Illuminate\Http\Request $request) {
$input = $this->request->all();
$a1 = $input['username'];
$a2 = $input['reg_no'];
$newngo = new ngosignup; //Replace ngosignup with your Model name.
$newngo->name = $a1; //name and reg_no should be column name
$newngo->reg_no = $a2;
$newngo->save(); //this will add these values into your DB
}
You can do this way.. Easier and Flexible.. You can add validator.. Refer to Laravel docs on their official site :)
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\ngosignup;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class ngosignupController extends Controller
{
public function index() {
$ngo = ngosignup::first(); // this shows first row of table..you can use get() instead of first to get all table as collection.
$data= array(
'ngo ' => $ngo
);
return View('index', $data);
}
Then on Index.Blade.php File.. you can display data from ngosignup table like
{{ $ngo->email }} // replace email with which data to display. if ollection.. use foreach loop to display all data.
Refer to Laravel docs.. they list all methods available..

Laravel5 Eloquent custom method return array

I have a static method in my User model which counts something, i am using a raw statement:
static function countOrders($userId)
{
$sql = "SOME CUSTOM-COMPLICATED QUERY";
$result = \DB::select( \DB::raw( $sql ) );
return $result; // <-- toArray() ? returns Exception!
}
Somewhere in my controller:
$orders = User::countOrders(*USER-ID*);
How can I get an array with records as arrays and not objects without modifying the global configuration for the FETCH method?
You don't need to run toArray().
When executing raw queries select returns array, it's stated in the docs:
The select method will always return an array of results.
static function countOrders($userId)
{
$sql = "SOME CUSTOM-COMPLICATED QUERY";
$result = \DB::select( \DB::raw( $sql ) );
return $result;
}

codeigniter pass variable from controller to model

simple issue I presume.
My controller is getting the if to display from the url using $this->uri->segment(3). This will always be a single value. I am putting this in an array to pass to the model with:
$customerid = array(
'id' => $this->uri->segment(3)
);
The controller syntax is below:
function confirm_delete_customer()
{
$data['title']="Confirm Customer Deletion";
$customerid=array(
'id'=>$this->uri->segment(3)
);
//query model to get data results for form
$data=array();
if($query=$this->model_master_data->get_customer_records_to_delete()){
$data['records']=$query;
$this->load->view("master_data/view_master_data_header",$data);
$this->load->view("master_data/view_master_data_nav");
$this->load->view("master_data/view_content_master_data_confirm_customer_deletion",$data);
$this->load->view("master_data/view_master_data_footer");
}
I am then trying to access this array value and pass it to my model to process. If I hard code the array into the model it works as per below syntax:
Model - Manual Syntax is:
function get_customer_records_to_delete()
{
$query = $this->db->get_where('customers', array('id'=>43));
return $query->result();
}
if I try replace this with the array from my controller it fails with error:
Undefined variable: customerid
idea of model that I want to get working:
function get_customer_records_to_delete()
{
$query = $this->db->get_where('customers', $customerid);
return $query->result();
}
I have a feeling it is something small. however is this the best way to get a single record from the database in order to output to a view?
Thanks in advance for the assistance.
The best way to do that is:
function confirm_delete_customer()
{
$data=array();
$data['title']="Confirm Customer Deletion";
$customerId = $this->uri->segment(3);
//Prevent SQL injections
if(!is_numeric($customerId) || empty($customerId)) {
show_error("Bad Request");
}
$query = $this->model_master_data->get_customer_records_to_delete($customerId);
if ($query){
$data['records']=$query;
$this->load->view("master_data/view_master_data_header",$data);
$this->load->view("master_data/view_master_data_nav");
$this->load->view("master_data/view_content_master_data_confirm_customer_deletion",$data);
$this->load->view("master_data/view_master_data_footer");
}
}
and then you can simply call:
function get_customer_records_to_delete($customerId)
{
$query = $this->db->get_where('customers', array('id'=>$customerId));
return $query->result();
}
at your model.
You need to pass the value as an argument to the function so it can access it.
Ex:
get_customer_records_to_delete($customerid)
{
// now $customerid is accessible
$query = ....;
return $……;
}
You should heavily rely on function parameters. Grab the customer id from the controller and send it to the model. Moreover, you can use row() to get a single result from the database.
Controller:
function confirm_delete_customer(){
$data['title']="Confirm Customer Deletion";
$customerid=$this->uri->segment(3);
//query model to get data results for form
$data=array();
if($query=$this->model_master_data->get_customer_records_to_delete( $customerid)) //you are sending customer id as a parameter here
$data['records']=$query;
$this->load->view("master_data/view_master_data_header",$data);
$this->load->view("master_data/view_master_data_nav");
$this->load->view("master_data/view_content_master_data_confirm_customer_deletion",$data);
$this->load->view("master_data/view_master_data_footer");
}}
Model
function get_customer_records_to_delete($customerid)
{
$query = $this->db->get_where('customers', array("id"=>$customerid)); //you are using the customer id sent from the controller here
return $query->row(); //this will return a single row
}
Old thread but the answer is to declare the variable as "public" in the controller (i.e. public $customerid;), in which case it'll be available to your model. In some cases it's probably safer to explicitly pass as an argument. However, when you have several variables, it's useful to have the option to declare them instead.

Getting the id of last inserted record

I'm trying to get the id of last inserted record in the Db. But i'm getting the error
Parse error: syntax error, unexpected T_RETURN in Z:\www\CI4\application\models \report_model.php on line 69
my model:
function getLastInserted() {
$query ="SELECT $id as maxID from info where $id = LAST_INSERT_ID()"
return $query; //line 69
}
my controller:
function index()
{
$id=$this->report_model->getLastInserted();
$this->load->view('u_type1',$id);
}
Assuming you are using the CI database library, you can use $this->db->insert_id().
function getLastInserted() {
return $this->db->insert_id();
}
I think you are missing a ; on line 67 after the last ".
if you want to get last id without insert function
$this->db->select('id')->order_by('id','desc')->limit(1)->get('table_name')->row('id');

Resources