how to select store procedure function genereteID in codeigniter? - php

I want to make a generated ID to use the function store procedure, but I am confused how to display generete ID using CodeIgniter.
Generete ID in store procedure function 'PenjualanGenIdFunc':
BEGIN
DECLARE kodebaru CHAR(15);
DECLARE urut INT;
SET urut = IF(nomer IS NULL, 1, nomer + 1);
SET kodebaru = CONCAT("PJL", LPAD(urut, 12, 0));
RETURN kodebaru;
END
I call in model with the code:
function getKodePenjualan(){
$query = $this->db->query("select PenjualanGenIdFunc('kodebaru') AS kodepenjualan");
return $query->row_array();
}
in controller :
$data['kodepenjualan'] = $this->mwebsite->getKodePenjualan();
and in view :
<?php echo $kodepenjualan['kodepenjualan'];?>
From the above code, generate ID already show with code: PJL000000000001, but when I will buy again. the code would not be PJL000000000002, PJL000000000003 and etc.
how to call a store procedure function for generete id ??
Please help me

First, if you want to call a SP, you need to call like this
$this->db->query("call PenjualanGenIdFunc()");
In your SP you must have something like this
CREATE PROCEDURE My_Insert
BEGIN
INSERT INTO My_Table (col1)
VALUES (#col1)
SELECT #new_identity = SCOPE_IDENTITY()
SELECT #new_identity AS id
RETURN
END
but if you want to get the last id insert using CI, you can use
$this->db->insert('table', array('value1' => $value1));
return $this->db->insert_id();

Related

Calling stored procedures with an OUT parameter in PHP [duplicate]

This question already has answers here:
PHP: Calling MySQL Stored Procedure with Both INPUT AND OUTPUT Parameters (NOT "INOUT")
(2 answers)
Closed 3 years ago.
To call a Stored procedure with an IN parameter is easy like
CREATE PROCEDURE `catalog_delete_product`(IN `inProductId` INT) BEGIN DELETE FROM product_attribute WHERE product_id = inProductId; DELETE FROM product_category WHERE product_id = inProductId; DELETE FROM shopping_cart WHERE product_id = inProductId; DELETE FROM product WHERE product_id = inProductId; END
You can see that it is as easy as that. But how do we call an OUT parameter in MySQL Stored parameter and use it in PHP?
As an example to illustrate it, I will a real world practical example(inserting data into an order table and returning the lastInsertId).
CREATE PROCEDURE `shopping_cart_create_order`(IN `inCartId` INT(11), OUT `newOrderId` INT(11)) BEGIN
DECLARE newOrder int;
-- Insert a new record into orders and obtain the new order ID
INSERT INTO orders (created_on) VALUES (NOW());
-- Obtain the new Order ID
SELECT LAST_INSERT_ID() INTO newOrder;
SET newOrder = newOrderId;
END
At PHP level// Probably at the Model/Entity level First, we need to execute the
shopping_cart_create_order()
stored procedure. Which might probably be in a function.
Second, to get the last order id, we need to query it from the variable
#oid
. It is important that we must call the method
closeCursor()
of the PDOStatement object in order to execute the next SQL statement.
function query($pdo, $sql, $parameters = []){
$query = $pdo->prepare($sql);
$query->execute($parameters);
return $query;
}
function create_order($pdo, $cart_id){
// Binding the parameters
$parameters = [':cart_id' => $cart_id];
// calling stored procedure command
$sql = 'CALL shopping_cart_create_order(:cart_id)';
// prepare for execution of the stored procedure, pass value to the command
and execute the Stored Procedure
$query = query($pdo, $sql, $parameters);
// Then close Cursor. It is important for you to close it.
$query->closeCursor();
// execute the second query to get last insert id
$row = $pdo->query("SELECT #oid AS oid")->fetch();
return $row;
}

PHP (Grocery CRUD) | Mysql Generate an unique and random number between two numbers

I have a table created in Mysql with this colums
secretNumber (Primary key & AI)
Name
Date
etc...
My idea is when I'm going to add a new item to this table, automatically generate a "secret number" but must has 3 requirements:
Unique number
Randon number everyime I add a new item
between 0-1000000
Tried to use funtions like uniqid(); and mt_rand(); but without success.
you can create tmptable for between 0-1000000
when you insert to the table, use from tmptable, after than you must delete that using row from this table.
or forward query but this is slowly because every time creating temp table. if you create temptable once, so it could be fast process.
CREATE TEMPORARY TABLE IF NOT EXISTS listtable(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, tmp INT NOT NULL);
SET #s = CONCAT('INSERT INTO listtable (tmp) VALUES ',REPEAT('(1),',1000000),'(1)');
PREPARE stmt1 FROM #s;
EXECUTE stmt1;
SELECT id FROM listtable WHERE id NOT IN(select id from your table) order by rand() limit 1;
DROP TABLE listtable;
The logic first : In order to achieve this you have to add a callback_before_insert() function in your grocery crud controllers' method. Inside this callback function you will create the random number you want, then add it to the $post_array variable and then return the $post_array back to your controllers' method (There are already examples on this at grocery cruds' official page).
So, somewhere in your controller you add this :
function _create_unique_secret_number()
{
/*Create a random secret_Number between 0 and 1000000
* and assign it to a variable
*/
$random_unique_secret_number = mt_rand( 0, 1000000 );
/* Now make sure that your random secret number is not already "in use"
* which means that the generated id is already stored in your table.
*/
$query = $this->db->where( 'secretNumber', $random_unique_secret_number )
->get_where( 'your_table_name_goes_here' );
if( $query->num_rows() > 0 )
{
$query->free_result();
// Try again in case the randomly generated number above is in use
return $this->create_unique_secret_number();
}
$post_array['secretNumber'] = $random_unique_int;
return $post_array;
}
/* And finally call the function inside your controllers' method.
* I mean inside the method that is handling your table.
*/
$crud->callback_before_insert( array ($this, '_create_unique_secret_number') );
You can then access the generated number in your grocery crud controller by accessing theenter code here $post_array['secretNumber'] value ..

error code 1414 occurs in mysql when i call stored procedure with ouput parameter

I'm trying to call a stored procedure (SP) from my codeigniter code but one of the parameters I defined in the Mysql SP is a OUTPUT parameter which is giving me some issues when calling the SP. Does anyone know the correct way to call the Sp from the PHP code with a OUTPUT parameter involved. The code is below:
MySql:
DROP PROCEDURE IF EXISTS usp_check_user_exist;
DELIMITER $$
CREATE PROCEDURE usp_check_user_exist
( IN email VARCHAR(200),
OUT result BIT(1) )
BEGIN
SET result = EXISTS(SELECT 1 FROM tbl_users WHERE user_email = email
LIMIT 1);
SELECT result;
END
Codeigniter/php:
public function check_email($email) {
$data = array(
'email' => $email,
'#result' => #result
);
$sp = "CALL usp_check_user_exist (?,?)";
$result = $this->db->query($sp, $data);
if($result) {
return TRUE;
} else {
return FALSE;
}
}
The error I got:
You have error in your stored procedure. Please check correct defination described below.
DELIMITER $$
DROP PROCEDURE `usp_check_user_exist`$$
CREATE PROCEDURE `usp_check_user_exist`(IN email VARCHAR(200))
BEGIN
DECLARE result TINYINT DEFAULT 0;
SET result = EXISTS(SELECT 1 FROM tbl_users WHERE user_email = email 1);
SELECT result;
END$$
DELIMITER ;
Also if you want to user your current Stored Procedure than while calling from PHP use statement like describe below.
call usp_check_user_exist('example#domain.com',#out);
Let me know if it not works.

How to get last inserted row ID from wordpress database with trigger which increment ID

I use Wordpress with a database. My problem is that I want to retrieve the inserted ID when using wpdb-> insert. I want to clarify that I increment the ID using a database trigger because my table is a relative entity. I was thinking of creating a procedure that I would call after my insertion.
My trigger
BEGIN
DECLARE num INTEGER;
IF NEW.id IS NULL THEN
SET num =
(
SELECT MAX(id) + 1
FROM ab_autreFrais
WHERE idDevis = NEW.idDevis
);
SET NEW.id = num;
ELSEIF NEW.id = 0 THEN
SET num =
(
SELECT MAX(id) + 1
FROM ab_autreFrais
WHERE idDevis = NEW.idDevis
);
SET NEW.id = num;
END IF;
END
There is the LAST_INSERT_ID() function that you can use instead of the trigger. Also you can get this value through an output parameter of a stored procrdure.
Or you could use auxiliary table or a global variable to put id value from the trigger. For example:
...
SET NEW.id = num;
UPDATE `SysData` SET `LastID` = num;
...
#Alexander
UPDATE ``SysData`` SET ``LastID`` = num; Does not work on MySQL SysData is not exist. I used SET SESSION last_insert_id = num in sql on phpmyadmin it work but with wpdb when i call last_insert_id() it return 0

error getting data procedure in codeigniter

I created a stored procedure, which saves values ​​in a table temporal.y then I show with the "select " but only in my sqlserver works well . when you call the procedure in codeigniter I generated an empty array.
THIS IS MY PROCEDURE IN CODEIGNITER
function verificacion_ocupados($codigo,$llave_maestra){
$sql = "sp_verificacionocupados ?, ?";
$query = $this->db->query($sql,array($codigo, $llave_maestra));
$data = $query->result();
$query->free_result();
return $data;
}
THIS IS MY PROCEDURE
CREATE PROCEDURE [dbo].[sp_verificacionocupados]
#codigo int,
#llave_maestro varchar(50)
AS
DECLARE #finicio date;
DECLARE #ffinal date;
DECLARE #codigo_dias int;
DECLARE #no VARCHAR(100);
create table #pivote(
code int
);
SET #no='veremos';
BEGIN
SELECT #ffinal=Oel_Fecha_Fin,#finicio=Oel_Fecha_Inicio
FROM Operaciones_Especiales_Llave
where Em_Codigo=#codigo and Oel_Estado=2 and Th_Llave=#llave_maestro ;
IF ##ROWCOUNT>0
BEGIN
INSERT INTO #pivote VALUES (2);
END
END
SELECT code from #pivote;
GO
This is just one example of a much larger consultation I am doing .
I think the problem is in the temporary table and as I call to return data.
Who has an idea what is the problem ? . Thanks in advance
change it as following.
function verificacion_ocupados($codigo,$llave_maestra)
{
$sql="sp_verificacionocupadose ?, ?";
$query=$this->db->query('call sp_verificacionocupadose("$codigo","$llave_maestra")'));
$data=$query->result();
$query->free_result();
return $data;
}

Categories