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()));
}
Related
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;
SELECT statements function OK and very fast between my php scripts and Oracle database. But UPDATE satements take forever to run, even a small query updating one row leaves the web browser loading the page for minutes.
This is the sample code that i want to execute from localhost. but the page is loading forever...
The sample code is:
$connect = oci_connect("SYSTEM","admin","XE");
if($connect) {
//echo 'connected';
$qry = oci_parse($connect,"UPDATE USER SET PASSWORD='1234' WHERE USERNAME='abc'");
$res=oci_execute($qry,OCI_COMMIT_ON_SUCCESS);
if($res){
echo "successfully updated";
}
}
else {
echo 'Not connected';
}
Two methods to debug your issue -
Check your query log - If the query is running as you are expecting.
If you are using Mysql this link here can help ->
How can I start and check my MySQL log?
If oracle -> https://docs.oracle.com/cd/E12032_01/doc/epm.921/html_techref/config/querylog/qlovervw.htm
It could be a issue of your development environment.
It also depends on your development environment configured properly.
You can start from your php configuration file(php.ini).
And do edit more details to your question.
I know this is not the best setup, but I'm stuck with it and cannot change it.
PHP connects to a local MS Access DB (.mdb) to log certain activities being done by the script. This works fine when only one instance of the script is running. However, if run two instances, I occasionally get the following error:
odbc_exec(): SQL error: [Microsoft][ODBC Microsoft Access Driver] Could not update; currently locked., SQL state S1000 in SQLExecDirect
This only happens intermittently so I'm assuming it's only when the two scripts both happen to be trying to write to the same table at the same time. I never had this issue with other DBs such as MySQL. How can I tell PHP/ODBC/Access to either not lock or try again if it is locked?
I also usually have the Access DB open on my screen for troubleshooting purposes.
odbc_exec() returns FALSE if the query fails, so you could just check the result of the query and keep trying until it succeeds:
$sql = "UPDATE [Clients] SET [Position]='somewhere' WHERE [ID]=1";
while (TRUE) {
$result = odbc_exec($conn, $sql);
if ($result) {
break;
}
else {
$lastError = odbc_error();
if ($lastError != "S1000") {
echo "ODBC error $lastError";
break;
}
}
sleep(1);
}
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)
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