sqlsrv UPDATE statement runs but doesn't update DB - php

I have an issue where my PHP sqlsrv UPDATE statement runs and doesn't return any errors but nothing in the DB ever changes and the row is not actually updated. Is there something I am missing that would allow this query to appear to run successfully but not update the row?
I have checked that the update statement runs in SQL server management studio and it updates the row.
$visitquery = "UPDATE tblVisit SET CalledInBy='WINNER' WHERE VisitID='3679061'";
$visitClose = sqlsrv_prepare($connect,$visitquery);
if( sqlsrv_execute( $visitClose))
{
echo "Statement executed.\n <br />";
}
else
{
echo "Error in executing statement.\n";
die( print_r( sqlsrv_errors(), true));
}

Thanks #JonathanAmend
sqlsrv_begin_transaction was opened but wasn't calling sqlsrv_commit.
http://www.php.net/manual/en/function.sqlsrv-commit.php

Make sure that your script has permission to access the correct database or nothing will happen to the tables.
So first, establish a connection to the database then specify the database that contains your table.
In your setup, add this line above your code.
$connect = sqlsrv_connect(server format goes here,array("Database"=>name of database containing tblVisit in quotes goes here,"UID"=>username to access database goes here,"PWD"=>password to access database goes here));
For each value, enclose them with quotes since they are strings.
There is more information on how to make the code here:
See this (at php.net)

Related

Backup and restore SQL server database using php

I wanted to make a simple website, which can open, show, and run sql server queries, just like executing queries from sql server management studio. It already can execute some queries like select (then show it as a table), insert, update, delete, including when i use where/group/order statement.
But, when I doing backup on my database with query :
BACKUP DATABASE 'mydb' TO DISK='pathname\filename.bak' WITH INIT/NOINIT
It can only backup the database once, and then when I execute the query with the same inputs, it got out with no error, but also no file backups produced from the execution. I don't know why, but when i'm executing with the same query from sql server management studio (with different filename so that the previous file didn't get overwritten), it execute without error and creating another file backup.
The code :
php
$sql = "ALTER DATABASE $db_name SET RECOVERY FULL";
$stmt = sqlsrv_query($conn, $sql);
if($stmt === false)
{
die(print_r(sqlsrv_errors()));
}
else
{
echo "Recovery model set to FULL";
}
if($_POST['type']=="Backup Full")
{
$query="BACKUP DATABASE $db_name TO DISK='$file\\$filename.bak' WITH
NOINIT;";
echo "<br>".$query."<br>";
$stat=sqlsrv_query($conn,$query);
if($stat == false)
{
echo "Error to retrieve info, THIS IS THE ERROR : <br />";
die(print_r(sqlsrv_errors()));
}
else
{
echo "Success!";
}
}
It create a new file .bak filled with my database backup
It returns error inside the 'if'
When i tried to run the code again with the different filename, it didn't create anymore .bak file.
When i restarted my PC, things back to normal (creating another .bak again)
It seems there's a solution here. Your issue it happened to me also but in my case sometimes the backup was created and sometimes no and I guess that the backup process fails when php executes and it exits before the ending backup process, therefore, it kills the connection in the middle of backup process. I realized that to execute a sql sequence of no-query type, it has to be consumed with the instruction sqlsrv_next_result till there's no more results.
You should use this snippet in order to execute the backup query successfully.
$query="BACKUP DATABASE $db_name TO DISK='$file\\$filename.bak' WITH NOINIT;";
if ( ($stmt = sqlsrv_query($conn, $query)) )
{
do
{
} while ( sqlsrv_next_result($stmt) ) ;
sqlsrv_free_stmt($stmt);
}else{
die(print_r(sqlsrv_errors()));
}

mysqli_commit fails when select statement is added

Problem:
Unable to store data with mySQL stored procedure with mysqli_begin_transaction.
Details:
The below code will do simple insert and select using mysql stored procedure. Code runs fine without select statement. However once the select statement is added, it won't commit any data even the query returns success at PHP side.
Snippets (PHP):
$DB_DRRM_SQLI = mysqli_connect("localhost","root","", "sandbox_db");
mysqli_begin_transaction($DB_DRRM_SQLI);
$SQL_QUERY_CODE = "CALL SANDBOX_TEST()";
$DB_QUERY = mysqli_query($DB_DRRM_SQLI, $SQL_QUERY_CODE);
// ERROR REPORTING
if($DB_QUERY === false)
{
echo mysqli_error($DB_DRRM_SQLI);
mysqli_rollback($DB_DRRM_SQLI);
}
else
{
echo 'success';
mysqli_commit($DB_DRRM_SQLI);
}
exit;
Snippets (mySQL Stored procedure):
BEGIN
INSERT INTO
`sandbox_table`
(
`SOME_STRING`
)
VALUES
(
'ABCDEFGHIJKL...'
);
SELECT
LAST_INSERT_ID() AS INSERTED_ID,
'ABCDE...' AS OTHER_PARAMS;
END
Database (Table sandbox_table):
RECORD_PRIMARY_ID (Int - Auto increment)
SOME_STRING (Varchar - 500 length)
Spec:
PHP version: 5.6.14
10.1.8-MariaDB
Storage Engine: InnoDB
Notes:
If transaction is made at stored procedure works fine, but I need a PHP managed transaction to handle multiple query requests and response depending on the result of query.
(It can be a possible last resort if there's no other solution, where I need to convert whole PHP code to stored procedure and need pass tons of parameter)
Methods Tested:
Tried with other PHP version 7.0.9 with same result (10.1.16-MariaDB)
Tested with new database with no other data except sandbox_tableand above stored procedure.
Tested without additional include libraries (tested with purely on above snippets).
Solution:
It was caused by Commands out of sync error at mysqli_commit. Seems the mysqli won't allow committing transaction while the query is open, which happens if you add select statement to above stored procedure.
So to handle this, it must close the query first or put the query to buffer.
Snippets (PHP):
// SQL Database
$DB_DRRM_SQLI = mysqli_connect("localhost","root","", "sandbox_db");
mysqli_begin_transaction($DB_DRRM_SQLI);
$SQL_QUERY_CODE = "CALL SANDBOX_TEST()";
$DB_QUERY = mysqli_query($DB_DRRM_SQLI, $SQL_QUERY_CODE);
// ERROR REPORTING
if($DB_QUERY === false)
{
echo mysqli_error($DB_DRRM_SQLI);
mysqli_rollback($DB_DRRM_SQLI);
}
else
{
// Must free current query result before committing transaction
#mysqli_free_result($DB_QUERY);
#mysqli_next_result($DB_DRRM_SQLI);
if(mysqli_commit($DB_DRRM_SQLI) === false)
{
echo mysqli_error($DB_DRRM_SQLI);
}
else
{
echo 'success';
}
}
exit;

sql update not changing data in DB

I made a simple update query using PDO in PHP :
$pdos = connect_db();
$pdos->beginTransaction();
try {
$query = "UPDATE `myo`.`question` SET `intitule` = 'Question azeerrr' WHERE `question`.`id` = 1";
$pdo = $pdos->prepare($query);
$pdo->execute();
return $pdo->rowCount();
catch (Exception $e) { print_r ($e); exit (); }
Which doesnt seem to work (the data is not changed in the database) even though i get no error message and even receive "1" from rowCount() meaning the update was successful.
And also, if i copy and paste this query in PHPmyadmin and run it, it works and the row is modified,
Could it be something about rights to execute an UPDATE from my website and not beeing the same as when you are logged into PHPmyadmin?
EDIT :
FIXED : thanks for you help : PDO::commit(); was needed to close my PDO::beginTransaction();
As you begin a transaction with $pdos->beginTransaction(); I'm pretty sure that you need commit it using $pdos->commit();
See the documentation for more information.
If you are using PDO's transaction, you must commit your changes to apply the modifications in your database.
See PDO::commit() function.
Even if you update a record with new values or with existing values, MySql always returns 1 in both the cases....

PHP prevent die before executing full code

I have code as below where I am redirecting the user at the end but sometimes it seems that the output variable is not getting set or insert query is not getting executed . So is there any way I can wait for all the operations to be completed before the die statement is executed.
Thanks
$diff=levenshtein(strtolower($str1),strtolower($str2));
if($diff<=2)
{
$output="ok";
}
else
{
$output="Not ok";
}
$query="INSERT INTO `table` (`sn`, `output`) VALUES (NULL,'$output')";
$result=mysqli_query($con,$query);
header('Location: http://www.domain.com/');
die;
There may be several reasons why it doesn't work.
The first one and most obvious is that is enough to have only one simple warning on your page (variable X is not set) and this will broke your header() command. It would say that headers have been already set.
The second problem is that sometimes the server is so busy answering other request and your $con variable will be a Boolean false instead of a reliable database connector, therefore your query could fail because of this too.
I encountered both situations in real life and I solved them by ensuring that every variable is set before use it and by checking if the query was executed successfully.
You can check if a variable is set by using this code:
if (!isset($variable)) $variable = "set me here";
You can check if your query was succesfully executed by adding this:
if (!$result) {
//do something here in case your query failed
}

Pass variable data from PHP to shell_exec command

I have a script that clones tables on to uniquely named MySQL databases from a master sql dump file . Each account has their own database, but the table structure is the same for all accounts. My solution was to dump the master database table and then through PHP shell_exec, run the MySQL controller cmd (mysql) to populate the newly created database with default tables.
At Issue: The process works but only when I hard code the accounts unique database name in the master sql dump file.
However, "USE acct_dbID" line inside the master sql file needs to be dynamically set at runtime.
Here is the code:
include('.dbase_credentials'); //constants for connection object
//using PHP built in connection class mysqli
$mysqli = new mysqli(DB_HOST,DB_UNAME,DB_UPWORD,DB_NAME);
if ($mysqli->connect_errno){
echo "Failed to open database connection: ".$mysqli->connect_error;
exit();
}
$dbID=$varNum; //variable, number ID generated earlier in the account setup process
//create database, doesnt return a resultset, no need for object var here
if ($mysqli->query("CREATE DATABASE acct_".$dbID) === TRUE){
//if dbase was created, clone the tables
$res = shell_exec('mysql -u dbaseUser --password=`cat /path/to/pass` -e "source /path/to/master_tables.sql" acct_'.$dbID);
//provide some UI feedback, shell_exec returns null on failure
if ($res!=null){
echo "The tables were cloned!";
}else{
echo "The cloning process failed!";
}
}else{
echo "no database created.";
}
So again, master_tables.sql needs variable data passed it at runtime so the "USE acct_dbID" can be specific to each new account.
Any thoughts are appreciated.
rwhite35
knittl had the right direction for what I need to do. See the comment conversation above. Thanks knittl.
Here is the new code block using multi_query and file_get_contents.
if ($mysqli->query("CREATE DATABASE acct_".$dbID) === TRUE){
$acct="acct_".$dbID;
$query = "USE ".$acct.";";
$query .= file_get_contents('/path/to/master_table.sql');
$result=$mysqli->multi_query($query);
}
Now account can be variable and multi_query will run each query statement in the string. I probably lose some efficiency but gain the ability to clone tables for each new account. The only additional edit made was to the master_table.sql. I removed all the comments that the dump process adds.
Thanks,
rwhite35

Categories