I need to call a stored procedure to insert the data to sql and it return a value with output parameter
like
CREATE PROCEDURE InsertInfo
#userid VARCHAR(100),
#login_time DATETIME,
#IsSuccuess BIT,
#loginid INT OUTPUT
AS
BEGIN
INSERT INTO Audit_LoginLogoutAttempt(UserID,Login_Time, IsSuccuess, DateCreated) VALUES (#userid,#login_time,#IsSuccuess, GETDATE())
SET #loginid = ##IDENTITY
END
GO
How to send input and output parameters using PHP
$stmt = $conn->prepare("{CALL InsertInfo(?, ?, ?, ?)}");
$stmt->bindParam(1, $UserID);
$stmt->bindParam(2, $LoggedInDateTime);
$stmt->bindParam(3, $IsSuccuess);
$stmt->bindParam(4, $get_id, PDO::PARAM_INT, 32);
$stmt->execute();
echo $get_id;
I tried like this but I'm not getting desired value from $get_id
You should bind your parameter as an OUTPUT parameter. If you have output parameters in your stored procedure and stored procedure returns recordsets, you need to fetch all recordsets to get output values.
<?php
# Statement
$stmt = $conn->prepare("{CALL InsertInfo(?, ?, ?, ?)}");
$stmt->bindParam(1, $UserID);
$stmt->bindParam(2, $LoggedInDateTime);
$stmt->bindParam(3, $IsSuccuess);
$stmt->bindParam(4, $get_id, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT, PDO::SQLSRV_PARAM_OUT_DEFAULT_SIZE);
$stmt->execute();
# Fetch results. Include this if your procedure returns resultsets (usually from SELECT statements):
#do {
# while ($row = $stmt->fetch()) {
# //
# }
#} while ($stmt->nextRowset());
# Get OUTPUT parameter value
echo $get_id;
?>
I usually put SET NOCOUNT ON as first line in stored procedures. This prevents SQL Server from passing the count of rows affected as part of the result set.
CREATE PROCEDURE InsertInfo
#userid VARCHAR(100),
#login_time DATETIME,
#IsSuccuess BIT,
#loginid INT OUTPUT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Audit_LoginLogoutAttempt(UserID,Login_Time, IsSuccuess, DateCreated) VALUES (#userid,#login_time,#IsSuccuess, GETDATE())
SET #loginid = ##IDENTITY
END
Related
I'm using PHP PDO with PostgreSQL for a new project.
Given the following function, how can I return the id of the row just inserted?
It doesn't work the way it looks now.
function adauga_administrator($detalii) {
global $db;
$ultima_logare = date('Y-m-d');
$stmt = $db->prepare("INSERT INTO site_admins (sa_nume, sa_prenume, sa_user_name, sa_password, sa_email, sa_id_rol, sa_status, sa_ultima_logare) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bindParam(1, $detalii['nume']);
$stmt->bindParam(2, $detalii['prenume']);
$stmt->bindParam(3, $detalii['username']);
$stmt->bindParam(4, md5(md5($detalii['parola'] . SIGURANTA_PAROLE) . SIGURANTA_PAROLE));
$stmt->bindParam(5, $detalii['email']);
$stmt->bindParam(6, $detalii['rol'], PDO::PARAM_INT);
$stmt->bindParam(7, $detalii['status'], PDO::PARAM_INT);
$stmt->bindParam(8, $ultima_logare);
$stmt->execute();
$id = $db->lastInsertId();
return $id;
}
From the Manual:
Returns the ID of the last inserted
row, or the last value from a sequence
object, depending on the underlying
driver. For example, PDO_PGSQL()
requires you to specify the name of a
sequence object for the name
parameter.
It should be something like:
return $db->lastInsertId('yourIdColumn');
[EDIT] Update link to doc
From the PHP manual:
For example, PDO_PGSQL() requires you
to specify the name of a sequence
object for the name parameter.
You could also use RETURNING in the INSERT-statement and fetch the INSERT-result like a SELECT result.
Previous answers are not very clear (PDO doc too)
In postgreSQL, sequences are created when you are using the SERIAL data type.
CREATE TABLE ingredients (
id SERIAL PRIMARY KEY,
name varchar(255) NOT NULL,
);
So the sequence name will be ingredients_id_seq
$db->lastInsertId('ingredients_id_seq');
I have two tables, reports and events, each table has a unique identifier called id with Auto increment, the problem is that the id in each table is not the same because a report can have events but maybe not. I would like to make a double insert but one column in each table must have an unique key. I do this with the following function:
function addactioneventuser(){
try {
$this->conn->beginTransaction();
$query = "INSERT INTO
" . $this->table_name . "
SET
case_id = ?,
from_to = 0,
action_id = ?,
accepted = 0,
message = ?";
// prepare query statement
$stmt = $this->conn->prepare($query);
// bind values
$stmt->bindParam(1, $this->case_id);
$stmt->bindParam(2, $this->action_id);
$stmt->bindParam(3, $this->message);
// execute the query
$stmt->execute();
// insert event query
$query2 = "INSERT INTO event_case
SET
title = ?, body = ?, class = ?, start = ?, end = ?, case_id= ?, worker_id = ?";
// prepare query statement
$stmt = $this->conn->prepare($query2);
// bind values
$stmt->bindParam(1, $this->title);
$stmt->bindParam(2, $this->body);
$stmt->bindParam(3, $this->class_event);
$stmt->bindParam(4, $this->start);
$stmt->bindParam(5, $this->end);
$stmt->bindParam(6, $this->case_id);
$stmt->bindParam(7, $this->worker_id);
// execute the query
$stmt->execute();
$this->conn->commit();
return true;
} catch (Exception $e) {
$stmt->rollBack();
return false;
}
}
The two inserts works perfectly but my problem is that the two ids for each table are not the same and as a consequence I can not delete at the same time an specific record from both tables and I don't know how to do it. I read about Cascade and other possible solutions but none of them seem pausible for my problem. I don't mind to create another column to use it as reference for both tables but I don't know how to do it in the above query.
Thank you in advance
Last insert id is $this->conn->insert_id;
You can get it after the operation and use the identifier.
For example to add it to the desired table
Okay, not too sure what I've done wrong, but I am having problems running a stored procedure using PDO. The procedure looks a little like this and runs perfectly as a stand alone.
CREATE PROCEDURE [dbo].[user_UserAdd]
#FirstName nvarchar(100),
#Surname nvarchar(100),
#EMail nvarchar(200),
#Password nvarchar(16)
AS
BEGIN
DECLARE #UserId uniqueidentifier
SET #UserId = NEWID()
INSERT INTO user_Data
VALUES (#UserId,
#FirstName,
#Surname,
#EMail,
#Password)
END
I know that the database connection works correctly as a select query returns the correct answers.
My php file contains the following :-
$stpro = $conn->prepare('EXECUTE user_UserAdd ?, ?, ?, ?');
$stpro->bindParam(1, $firstname, PDO::PARAM_STR, 100);
$stpro->bindParam(2, $surname, PDO::PARAM_STR, 100);
$stpro->bindParam(3, $email, PDO::PARAM_LOB, 200);
$stpro->bindParam(4, $password, PDO::PARAM_STR, 16);
// call the stored procedure
$returnvalue = $stpro->execute();
if (!$returnvalue)
{
return $stpro->errorInfo();
}
This always returns the same error message
["2"] = "An invalid PHP type was specified as an output parameter.
DateTime objects, NULL values, and streams cannot be specified as output parameters."
I have changed EXECUTE to just EXEC and to CALL and just get the same message. On checking the database it is definitely not inserting the new line of data, but at the same time the php page loads properly and does not kick any error messages regarding the stored procedure not running.
Sound like a binding error , although code looks correct.
You can try binding without specifying the type and leave it up to PDO:
$query = "EXECUTE user_UserAdd :firstname, :surname, :email, :password";
$stpro = $conn->prepare($query);
$stpro->bindParam(':firstname', $firstname);
$stpro->bindParam(':surname', $surname);
$stpro->bindParam(':email', $email);
$stpro->bindParam(':password', $password);
// call the stored procedure
$returnvalue = $stpro->execute();
Or just don't bind at all and see if it works:
$query = "EXECUTE user_UserAdd :firstname, :surname, :email, :password";
$stpro = $conn->prepare($query);
// call the stored procedure
$returnvalue = $stpro->execute(array(
':firstname'=> $firstname,
':surname'=> $surname,
':email'=> $email,
':password'=> $password,
));
Here is prepare update statement and I think I Have the Variable types out of whack, not sure.
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE `Calibration_and_Inspection_Register` SET `item_type` = ?, `location` = ?, `date_last_test` = ?, `serial_number` = ?, `date_next_test` = ?, `comments` = ?
WHERE `id`=?"))
{
$stmt->bind_param("issdsds",`$id`, `$item_type`, `$location`, `$date_last_test`, `$serial_number`, `$date_next_test`, `$comments`);
$stmt->execute();
$stmt->close();
}
Order is important if you are not using named parameters. Since id is last parameter in the statement, it needs to be the last in the list of bound parameters as well.
Back-ticks around your parameter variables names in bind_param() call are also probably giving you errors. It should look like this:
$stmt->bind_param("ssdsdsi",$item_type, $location, $date_last_test, $serial_number, $date_next_test, $comments, $id);
I'm using PHP PDO with PostgreSQL for a new project.
Given the following function, how can I return the id of the row just inserted?
It doesn't work the way it looks now.
function adauga_administrator($detalii) {
global $db;
$ultima_logare = date('Y-m-d');
$stmt = $db->prepare("INSERT INTO site_admins (sa_nume, sa_prenume, sa_user_name, sa_password, sa_email, sa_id_rol, sa_status, sa_ultima_logare) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bindParam(1, $detalii['nume']);
$stmt->bindParam(2, $detalii['prenume']);
$stmt->bindParam(3, $detalii['username']);
$stmt->bindParam(4, md5(md5($detalii['parola'] . SIGURANTA_PAROLE) . SIGURANTA_PAROLE));
$stmt->bindParam(5, $detalii['email']);
$stmt->bindParam(6, $detalii['rol'], PDO::PARAM_INT);
$stmt->bindParam(7, $detalii['status'], PDO::PARAM_INT);
$stmt->bindParam(8, $ultima_logare);
$stmt->execute();
$id = $db->lastInsertId();
return $id;
}
From the Manual:
Returns the ID of the last inserted
row, or the last value from a sequence
object, depending on the underlying
driver. For example, PDO_PGSQL()
requires you to specify the name of a
sequence object for the name
parameter.
It should be something like:
return $db->lastInsertId('yourIdColumn');
[EDIT] Update link to doc
From the PHP manual:
For example, PDO_PGSQL() requires you
to specify the name of a sequence
object for the name parameter.
You could also use RETURNING in the INSERT-statement and fetch the INSERT-result like a SELECT result.
Previous answers are not very clear (PDO doc too)
In postgreSQL, sequences are created when you are using the SERIAL data type.
CREATE TABLE ingredients (
id SERIAL PRIMARY KEY,
name varchar(255) NOT NULL,
);
So the sequence name will be ingredients_id_seq
$db->lastInsertId('ingredients_id_seq');