I'm in a vocational training right now and my task is to create a web-formula for accounting stuff. The server is running IIS 6.2 on Windows Server 2012 R2, PHP 7.2.1 and I finally got the MS PHP SQL Extension running.
Besides my code being a stackowerflow patchwork, it kinda works, only that I cant figure what I did wrong with the query. On submitting the formula it says Transaction rolled back, and I really don't know why. The query is, when pasted into MS SQL Server Management Studio, successfully executed, but not in the form.
$serverName = "server\sqlexpress";
$connOptions = array( "Database"=>"123", "UID"=>"456", "PWD"=>"xxx");
$conn = sqlsrv_connect( $serverName, $connOptions );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true ));
}
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* This is the query */
$sql1 = "INSERT INTO Person (Kundennummer, Vorname, Nachname, Strasse, Hausnummer, Etage, Email) VALUES (?, ?, ?, ?, ?, ?, ?)";
$params1 = array($kundennummer, $vorname, $nachname ,$strasse, $hausnummer, $etage, $email);
$query1 = sqlsrv_query( $conn, $sql1, $params1 );
/* This is where it rolls back the transaction */
if($query1) {
sqlsrv_commit( $conn );
echo "Transaction committed.<br />";
}
else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back.<br />";
}
sqlsrv_close($conn);
The Connection is working, because if i replace $sql1 with
$sql1 = "SELECT 'Hello world'";
it says commited.
Any guesses? Thanks alot, and, in case you seeing some more bad stuff happening in my code, feel free to correct me.
And suddenly i've got the answer.
When I added echo(print_r(sqlsrv_errors(), true)); to the code, it says "INSERT permission was denied on the object [...]", so I added permission to the user. Problem solved, thanks to this answer
Related
I'm working on an android app that requires connection to a database. I have the android part working but I'm having trouble with my php script.
<?php
$con = mysqli_connect(/This info is correct/) or die ("Unable to connect");
$gebruikersnaamOntvanger = $_POST["gebruikersnaamOntvanger"];
$idBetaler = $_POST["idBetaler"];
$bedrag = $_POST["bedrag"];
$saldoBetaler = $_POST["saldo"];
$response = array();
$response["success"] = "false";
$statement = mysqli_prepare($con, "SELECT idGebruiker, Saldo FROM Gebruikers WHERE Gebruikersnaam = ?");
mysqli_stmt_bind_param($statement, "s", $gebruikersnaamOntvanger);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $idGebruiker, $Saldo);
while($row = mysqli_stmt_fetch($statement)){
$idOntvanger = $idGebruiker;
$saldoOntvanger = $Saldo;
}
$saldoOntvanger += $bedrag;
$saldoBetaler -= $bedrag;
try {
$statement2 = mysqli_prepare($con, "INSERT INTO Transacties (idBetaler, idOntvanger, Bedrag, Datum, Uitgevoerd) VALUES(?, ?, ?, now(), 1)");
mysqli_stmt_bind_param($statement2, "iid", $idBetaler, $idOntvanger, $bedrag);
mysqli_stmt_execute($statement2);
$response["success"] = "success";
} catch(Exception $e) {
$response["success"] = $e->gettext;
}
echo json_encode($response);
?>
So the android part work and returns the JSON object correctly but nothing changes in the database. I have tried adding a try catch so I get what's the error but the try catch never works. The script alwayws returns success even if it didn't work. Please be aware I'm new to PHP and I have double checked the SQL queries and they should be correct. If you need more information please ask.
mysqli_* function dosn't throws exceptions. So your catch is never executed even on error. Change your code like this :
if(!mysqli_stmt_execute($statement2))
throw new Exception(mysqli_stmt_error($statement2));
When you'll see the error you can fix your code. May be add same error handling to mysqli_prepare and others
I think the issue was the use of iid in the binding for the insert query. It should either be iis or iii presumably. You tried using try/catch blocks but to my mind did not make full use of them - the creation of a prepared statement should be tested to see if it succeeds or fails ~ the outcome of which can be used in the try/catch logic to indicate faults. Excuse the mix of procedural and OOP style code
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST["gebruikersnaamOntvanger"], $_POST["idBetaler"], $_POST["bedrag"], $_POST["saldo"] ) ){
try{
$con = mysqli_connect(/This info is correct/) or die ("Unable to connect");
$gebruikersnaamOntvanger = $_POST["gebruikersnaamOntvanger"];
$idBetaler = $_POST["idBetaler"];
$bedrag = $_POST["bedrag"];
$saldoBetaler = $_POST["saldo"];
$response = array('success'=>false);
$stmt=$conn->prepare( 'select `idgebruiker`, `saldo` from `gebruikers` where `gebruikersnaam` = ?' );
if( !$stmt ) throw new Exception('unable to prepare select query');
else {
$stmt->bind_param( 's', $gebruikersnaamOntvanger );
$result=$stmt->execute();
if( !$result )throw new Exception('No results from select query');
else {
$stmt->store_result();
$stmt->bind_result( $idGebruiker, $Saldo );
while( $stmt->fetch() ){
$idOntvanger = $idGebruiker;
$saldoOntvanger = $Saldo;
}
$saldoOntvanger += $bedrag;
$saldoBetaler -= $bedrag;
$stmt=$con->prepare('insert into `transacties` ( `idbetaler`, `idontvanger`, `bedrag`, `datum`, `uitgevoerd` ) values(?, ?, ?, now(), 1)');
if( !$stmt )throw new Exception('Unable to prepare insert query');
else {
/* What is the value of $bedrag? integer, string?? */
/*
The binding iid was incorrect - perhaps iis or iii
*/
$stmt->bind_param('iis', $idBetaler, $idOntvanger, $bedrag );
$result = $stmt->execute();
$response['success']=$result;
}
}
}
echo json_encode( $response );
}catch( Exception $e ){
echo $e->getMessage();
}
}
?>
Please note that i tried all existing solutions and still haven't got output.
I have a php page that calls a Stored Procedure in SQL Server using sqlsrv functions. I have tried existing solutions but unable to solve my problem. When i execute this same SP in SQL Management Studio, it gives output of 31 rows. However, here in my code i am unable to get any row of data. Could someone advise on how to?
Here is my code:
$serverName = "(local)"; //serverName\instanceName
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$connectionInfo = array( "Database"=>"TESTDB");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
$AcCode = '18100017';
$StartDate = '2016/12/01';
$EndDate = '2016/12/31';
$CutAmt = -50000;
$IntRate1 = 2;
$IntRate2 = 3;
$sql = "EXEC dbo.uspGetBankInterest #AC_NO= ?, #AsOfDate= ?, #EndDate= ? ,#CutAmt= ?, #IntRate1= ?, #IntRate2= ?";
$stmt = sqlsrv_prepare($conn, $sql, array(&$AcCode,&$StartDate,&$EndDate,&$CutAmt,&$IntRate1,&$IntRate2));
$result=sqlsrv_execute($stmt);
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
if($result){
echo "SP Executed!";
}
$ctr=0;
$row_count = sqlsrv_num_rows( $stmt );
echo ' '.$row_count.'<br>';
while($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
print_r($stmt);
echo($row['STAT_DATE'].' '.$row['STAT_AMT'].' '.$row['INT_AMT']."<br>");
$ctr++;
}
echo 'The total number of records are:'.$ctr;
die();
}
else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
The output i get is:
SP Executed!
The total number of records are:0
When i executed, there was an output of 31 records and the data was displayed correctly. There is no problem in my SP. However, when i am trying it in php, no data is brought. How can i solve this problem?
I have the following object which I am parsing from Javascript to PHP via an AJAX post request.
What is the best way to safely insert this data into SQL using PHP?
All of the keys of the object exist as columns in a table. So I thought that I'd need to find a way to loop through the object and create a statement like:
insert into table (email, first_name, last_name) VALUES ('email#host.net', 'Joe', 'Bloggs'),('email2#host2.net', 'Fred', 'Flintstone')
However, I have a suspicion that this method would open me up to the risk of SQL injection.
I have heard of 'Prepared Statements' as a way to accomplish the this with mysqli however, I am not sure if this works in sqlsrv.
This is what I have so far:
<?php
$serverName = "server";
$connInfo = array("Database"=>"database", "UID"=>"sa", "PWD"=>"password");
$conn = sqlsrv_connect($serverName, $connInfo);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$json = file_get_contents("php://input");
$data = json_decode($json, true); /// <----- THIS IS THE OBJECT WHICH HAS BEEN PARSED FROM JS VIA AJAX
$sql = ""; /// <--- I need to create an insert statement???
/////Execute the statement
if($conn){
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}//end if
echo json_encode("Record created successfully. ");
}//end if
/////End of Execute the statement
}//end if
else{
echo json_encode("ERROR: record did not save correctly to MSSQL.");
die( print_r(sqlsrv_errors(), true));
}//end else
?>
I am using PHP 5.6 and SQL Server 2012 with a nonthreadsafe driver. I have an incredibly easy question I already know, but for some reason i am completely brain dead.
I have a basic SQL query that will can either return 1 row of data, or multiple.
There is only three fields with data. but I would like to be able to read off the data (this is going into a vXML ivr using Voice Server 4.0, but that is irrelevant to my question).
Here is my code:
<?php
$serverName = "localhost";
$connectionOptions = array("Database"=>"mydb");
/* Connect using Windows Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionOptions);
if( $conn ) {
echo "Connection established.";
}else{
echo "Connection could not be established.";
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT * FROM my_table WHERE SSN = 111111111";
//////I have no idea if I need this or not input appreciated
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
?>
All I would like to do is be able to retreive the information as rows, like
echo $row['field'];
echo $row['field2'];
echo $row['field3'];
ect.
would someone be able to point me in the right direction? I can only find mysqli examples, and those do not seem to work. Thanks!
I assume what you're looking for is sqlsrv_fetch_array
sqlsrv_fetch_array — Returns a row as an array
An Example:
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['field'].", ".$row['field2']."<br />";
}
PHP Manual: sqlsrv_fetch_array
I am new in the MSSQL. i have create a database in MSSQL. Now all is working fine like add/edit/delete. i am adding 3 record in 3 different table at the same time in same of different database.
I want to use Rollback in the database.
Suppose i am adding three record at the same time. First two work properly and last query find some issue in adding it in the table. At this time i want to remove the first two query which is inserted in the table.
can anyone help me for this issue ?
if you have another option to solve this issue then let me know
Thanks in advance
Use sqlsrv_begin_transaction() function to begin a transaction. Then, you can either commit it by calling sqlsrv_commit() function or roll it back by calling sqlsrv_rollback() function.
Example from php.net manual
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;
/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );
/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
SET Quantity = (Quantity - ?)
WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );
/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
sqlsrv_commit( $conn );
echo "Transaction committed.<br />";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back.<br />";
}
?>