I am currently trying to execute a stored procedure(Two INSERTS and a SELECT) through PHP. The stored procedure works (no errors are thrown). The values are even inserted into the given tables. We are storing the result in a JSON object but it is returning an empty array. When we execute the stored procedure containing only a SELECT it returns the correct values. All the names have been changed in our tables (may have missed some but our code runs). Can anyone shed light on why our array is not populating?
Here is our stored procedure
ALTER procedure
As
BEGIN
INSERT INTO TABLE1
(Loan_ID, Doc_ID, Borrower_Name, Docs_Drawn, Funder, First_Payment, Interest_Rate, Loan_Amount)
Select Loan_ID,
(SELECT (COUNT(*)) FROM TABLE WHERE A.Loan_ID = Loan_ID) AS Doc_ID,
Borrower ,[Date_Docs_Drawn]
,[Funder]
,[Payment_Date]
,[Interest_Rate]
,[Loan_Amount] from VIEW A
INSERT INTO TABLE2
(Loan_ID, Submitted_By, Event_Class, Event_Type, Event_Date, Doc_ID)
SELECT A.[Loan_ID],
'Program' AS Submitted_By
,'Collateral' AS Event_Class
, 'Outstanding' AS Event_Type
, CURRENT_TIMESTAMP AS Event_Date
, Doc_ID
FROM TABLE1 AS A
WHERE NOT (A.Loan_ID = ANY (SELECT Loan_ID FROM TABLE2))
SELECT [Loan_ID],[Doc_ID],[Borrower_Name]
,[Funder]
,[Docs_Drawn]
,[First_Payment]
,[Loan_Amount]
,[Interest_Rate]
FROM TABLE1
WHERE Loan_ID <> ALL
(SELECT Loan_ID FROM TABLE2
WHERE Event_Type <> 'Outstanding')
ORDER BY Funder
END
here is a rough sketch of our PHP
$query = "exec storedProcedure";
$result=sqlsrv_query($conn, $query);
$table = array();
while($row = sqlsrv_fetch_array($result)) {
$table[] = $row;
}
echo json_encode($table);
Try using SET NOCOUNT ON in your stored procedure. You are probably being limited by the results returned to the PHP from the SQL Server PHP driver, so you aren't getting the data from the SELECT statement.
Related
In my php code, I have a Mysql query:
SELECT COUNT(*)
to see if the record already exists, then if it doesn't exist I do an:
INSERT INTO <etc>
But if someone hits reload with a second or so, the SELECT COUNT(*) doesn't see the inserted record.
$ssql="SELECT COUNT(*) as counts FROM `points` WHERE `username` LIKE '".$lusername."' AND description LIKE '".$desc."' AND `info` LIKE '".$key."' AND `date` LIKE '".$today."'";
$result = mysql_query($ssql);
$row=mysql_fetch_array($result);
if ($row['counts']==0) // no points for this design before
{
$isql="INSERT INTO `points` (`datetime`,`username`,`ip`,`description`,`points`,`info`, `date`,`uri`) ";
$isql=$isql."VALUES ('".date("Y-m-d H:i:s")."','".$lusername."',";
$isql=$isql."'".$_SERVER['REMOTE_ADDR']."','".$desc."','".$points."',";
$isql=$isql."'".$key."','".$today."','".$_SERVER['REQUEST_URI']."')";
$iresult = mysql_query($isql);
return(true);
}
else
return(false);
I was using MyISAM database type
Instead of running two seperate queries just use REPLACE INTO.
From the documentation:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
For example if your key field is id then:
REPLACE INTO my_table SET id = 4 AND other_field = 'foobar'
will insert if there is no record with id 4, or if there is then it will replace the other_field value with foobar.
I am new to stored procedures, and i am having an issue with the results returned by the stored procedure not having any values when i call the stored procedure via PHP. When i manually make the call directly on the MySQL server it works fine and returns 5 values. When i call the procedure through php no values are stored in the binding variables.
Stored Procedure:
DELIMITER $$
CREATE PROCEDURE `TPE_GET_current_repair` (IN current_repair_vid VARCHAR(45))
BEGIN
SELECT current_repair_vid v1;
SELECT
sys_vendor.vendor,
receive_date,
tape_repair_problem_code.tape_repair_problem_reason,
sys_tape_type.tape_type,
sys_capture_location.capture_location
FROM tape_repair
INNER JOIN `sys_vendor` on tape_repair.vendor_id = sys_vendor.id
INNER JOIN `tape_repair_problem_code` on tape_repair.problem_code = tape_repair_problem_code.id
INNER JOIN `sys_tape_type` on tape_repair.tape_type_id = sys_tape_type.id
INNER JOIN `sys_capture_location` on tape_repair.capture_location_id = sys_capture_location.id
WHERE vid = current_repair_vid;
END
PHP:
$repairData = "CALL TPE_GET_current_repair('$vid')";
if ($stmt = $mysqli->prepare($repairData)) {
$stmt->execute();
$stmt->bind_result($rpr_vendor, $rpr_rcv_date, $rpr_problem, $rpr_tape_type, $rpr_capt_loctn);
$stmt->fetch();
}
I fixed the issue, i had forgotten about the first select statement and it was causing the statement to fail.
I have used bulk update to sync datas between two tables as below
$sqlProc="
UPDATE cards
SET cards.card_no = t2.card_number,
cards.expiry_date=t2.expiry_date OUTPUT INSERTED.Id AS 'updated_id'
FROM cards
INNER JOIN card_temp t2 ON (cards.account_no = t2.account_number
AND cards.customer_name=t2.customer_name)
WHERE cards.is_disabled='N'";
debug($this->Request->query($sqlProc));
Above query will also return Primary key of updated records usingOUTPUT INSERTED.Id AS 'updated_id' in sql server editor but when i debug the sql
debug($this->Request->query($sqlProc));
Then it return true for successful query and false for unsuccessful query.
Is there any idea to fetch updated_id to array , so that i can use those ids to another table
Well , I figured out finally . I created one intermediate table did the following
//inserted into temp_id (bridge table)
$sqlProc="insert into temp_id select * FROM (update cards
set cards.card_no = t2.card_number,cards.expiry_date=t2.expiry_date
OUTPUT INSERTED.Id AS 'updated_id'
from cards
inner join card_temp t2
on (cards.account_no = t2.account_number and cards.customer_name=t2.customer_name)
where cards.is_disabled='N'
) AS t";
$this->Request->query($sqlProc);
//fetch from intermediate table
$sqlSel="SELECT * FROM temp_id";
$arr=$this->Request->query($sqlSel);
//this array will fetch all updated id's
debug($arr);
$sqlDel="DELETE FROM temp_id";
$this->Request->query($sqlDel);
I have a procedure called SELECT_DESCRIPTION that receives an id and returns a Description field I need to show in my page.
Now I want to create a new procedure that having a number of ids coming from a select clause like this:
SELECT id FROM MYTABLE
Can pass it to the SELECT_DESCRIPTION procedure so I can have the same number of descriptions
If I was using php I would be doing something like this:
$sql=”SELECT id FROM MYTABLE”;
$result = mysql_query($sql) //using mysql to make the example faster but TSQL is what I use
or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
$newSql = "EXEC SELECT_DESCRIPTION #id = '$row[‘id’]'";
//do whatever with $newSql
}
But I need to use a procedure. Is is possible to do it? How can I do it?
Thanks a ton!
So you're wanting to do all of this in TSQL? Something like this would do it:
DECLARE #tmp TABLE (tmpID INT IDENTITY, tblID INT)
DECLARE #RecordCount INT,
#LoopCount INT,
#ID INT
INSERT INTO #tmp SELECT id FROM MYTABLE
SELECT #RecordCount = COUNT(*) FROM #tmp
SET #LoopCount = 1
WHILE #LoopCount <= #RecordCount
BEGIN
SELECT #ID = tblID FROM #tmp WHERE tmpID = #LoopCount
EXEC SELECT_DESCRIPTION #ID
SELECT #LoopCount = #LoopCount + 1
END
The #tmp table has an identity column that insures whatever data you're running the loop on has consecutive row numbers (1, 2, 3, 4, etc).
I am working on a system which keeps track of what was in the field, prior to it being updated. I'd prefer using a table for the previous data, but am open to other options. This is some sample code which would accomplish the task :
<?php
$initial_value = $_POST['some_value'];
$id =231212213; // some id
$stmt = $mysqli->prepare("SELECT column FROM table WHERE user=?")
$stmt->bindParam("s", $id);
$stmt->execute();
$stmt->bind_result($column);
$stmt->fetch();
if ($column !="") {
//edit : it doesnt matter to me whether the data is moved into a new table or column
$stmtA = $mysqli->prepare("UPDATE another_table SET backup_column=? WHERE user=?");
$stmtA->bindParam("ss", $column, $id);
$stmtA->execute();
$stmtB = $mysqli->prepare("UPDATE table SET column=? WHERE user=?");
$stmtB->bindParam("ss", $initial_value, $id);
$stmtB->execute();
}
?>
This is a pure mysql commands solution which you could modify your code to do:
1.) CREATE TABLE new_table_name LIKE old_table_name
2.) INSERT INTO new_table_name SELECT * FROM old_table_name
Done. ;-)
This way you have an exact backup of your table previously, and joins are very easy to see the differences:
SELECT a.*, b.* FROM old_table a JOIN new_table b ON a.id=b.id WHERE <criteria>;
EDIT
UPDATE BACKUP SET COLUMN = (SELECT COLUMN FROM TABLE WHERE user_id=#) WHERE user_id=#;