MSSQL database stuck in restoring state with PHP - php

I am trying to restore a database to a different server through PHP. I managed to execute all needed commands but the database keeps hanging in the 'Restoring...' state on the server.
I have searched and followed the answer on SQL Server: Database stuck in “Restoring” state with PHP (which leads to this article) but this did not work for me; I get an error when trying to change the environment to the newly recovered database.
Code:
sqlsrv_configure( "WarningsReturnAsErrors", 0 );
$connOptions = ["Database"=>"master"];
$sqlConnection = sqlsrv_connect("server_name\\SERVER", $connOptions);
sqlsrv_query($sqlConnection, "USE master");
$sql = "IF EXISTS(SELECT name FROM sys.databases
WHERE name = 'db_name')
DROP DATABASE db_name";
sqlsrv_query($sqlConnection, $sql);
$sql = "RESTORE FILELISTONLY FROM DISK='$path'";
$logicalNamesStatement = sqlsrv_query($sqlConnection, $sql);
$moveArray = [];
while($logicalNames = sqlsrv_fetch_array($logicalNamesStatement, SQLSRV_FETCH_ASSOC)){
if($logicalNames['Type'] === "D"){
$moveArray['MDF'] = $logicalNames['LogicalName'];
}
elseif($logicalNames['Type'] === "L"){
$moveArray['LDF'] = $logicalNames['LogicalName'];
}
}
$localDbPath = "c:\\Program Files\\Microsoft SQL Server\\MSSQL11.SERVER\\MSSQL\\DATA\\";
$sql = "RESTORE DATABASE db_name FROM DISK='$path'
WITH
MOVE '" . $moveArray['MDF'] . "' TO '" . $localDbPath . "db_name.mdf',
MOVE '" . $moveArray['LDF'] . "' TO '" . $localDbPath . "db_name_log.ldf',
REPLACE,
STATS=10";
sqlsrv_query($sqlConnection, $sql);
$sql = "RESTORE DATABASE db_name FROM DISK='$path' WITH REPLACE, RECOVERY";
sqlsrv_query($sqlConnection, $sql);
sqlsrv_query($sqlConnection, "USE db_name");
The error that comes back is:
[Microsoft][SQL Server Native Client 11.0][SQL Server]Database 'db_name' cannot be opened. It is in the middle of a restore.
Do you have any ideas on how I can solve this? The only authority on a workaround for the bug described in my previously linked article seems to be that exact article, which does not work as you can see.
Thanks!

I don't have 50 reputation yet, so feel free to move this to the comments section. I don't see your database names including brackets "[ ]". If you have any database names with spaces or special characters, you'll need the brackets to identify the object properly. And as Mitch already stated, based on what you are doing, there is no reason for two restore operations; just add the RECOVERY option into the first and be done with it.

Related

PHP - Problems on Change MySQL-enquiry from mysql_query to PDO

Last year I have taken over the support of a webpage. This page in parts is still written with mysql_querys, which is the reason the server still runs on PHP 5.6 (which causes unnecessary cost). To finally change the server to PHP 7.x, I'm actually working on change the scripts which still use mysql_query to PDO. In parts this worked without any problem. But now one of the scripts still won't work after a long search of mistakes. So I hope, that someone in this community can take a look at the script and help my finding the error.
The MysQL-query surely is correct and gives a result. So the problem must be at the PDO-syntax.
This was the Script how it is used till now (only the output is simplified by me):
$link = mysql_connect($sHost, $sUser, $sPass);
mysql_select_db($sDBName, $link);
$sql1 = "SELECT * FROM `" . $table . "` WHERE `index` = " . $_REQUEST['id'];
$erg1 = mysql_query($sql1, $link) or die("Fehler: " .mysql_error());
$result1[0] = mysql_fetch_array($erg1);
echo $result1[0]["kreis"];
Result:
Berlin
This is the script change to PDO now:
if(isset($_GET['id'])) {
$id = $_GET['id'];
} else {
die("Bitte eine ?id übergeben");
}
$pdo2 = new PDO(sprintf('mysql:host=%s;dbname=%s', $sHost, $DBName), $sUser, $sPass);
$utf8 = $pdo2->prepare("SET NAMES UTF8");
$result_check = $utf8->execute();
$table = "orte_bb";
$sql1 = "SELECT * FROM `" . $table . "` WHERE `index` = ?";
$statementbb = $pdo2->prepare($sql1);
$erg1 = $statementbb->execute(array($id));
while ($result1 = $statementbb->fetch(PDO::FETCH_ASSOC))
{
echo $result1['kreis'];
}
Result:
empty array
This means, that the PDO $statementbb seams to file no data set. The question, I can't answer to me, ist, why this happens.
I would be happy, when some can take a look and give me a clue.
Thanks
bagira41berl
Now I found the error myself (which stuck in the detail). The error is in the first PDO-line:
$pdo2 = new PDO(sprintf('mysql:host=%s;dbname=%s', $sHost, $DBName), $sUser, $sPass);
It's the variable, which is used for the database-name, where 1 letter is missed, which didn't stand out mutch. I korrected the syntax of this line to:
$pdo2 = new PDO(sprintf('mysql:host=%s;dbname=%s', $sHost, $sDBName), $sUser, $sPass);
And now it works.
Best reagards
baerlinerbaer

Duplicate items in MySQL database after editing code

I have a problem with my PHP code.
I am trying to make a level create function for a small game project me and another person are working on.
My code works.. but generates a lot of duplicates.
Here's the code: (Don't laugh at me for how vulnerable this is, this will be fixed eventually, THIS IS JUST TEST CODE AND WILL NEVER BE ON A PUBLIC SERVER IN ANY CIRCUMSTANCE, OK?)
$mysqli = new mysqli("localhost", "Username", "Password", "sys");
$SqlQuery = "INSERT INTO levels (levelname, levelauthor, leveldata)
VALUES(\"" . $_GET["levelName"] . "\", \"" . $_GET["levelAuthor"] . "\", \"" . $_GET["levelData"] . "\");";
$query2 = "SELECT * FROM levels WHERE leveldata = \"" . $_GET["levelData"] . "\";";
//echo "SELECT * FROM levels WHERE leveldata = \"" + $_GET["levelData"] + "\";";
$uresult = $mysqli->query($SqlQuery, MYSQLI_USE_RESULT);
$res2 = $mysqli->query($query2, MYSQLI_USE_RESULT);
if ($uresult) {
while ($row = $res2->fetch_assoc()) {
//This should always work. Lol
echo "(SUC)|ID:" . $row["levelid"];
}
}
After running this code, I expected to just check my database and be able to see the test I wrote, without duplicates.
I started the PHP development server and went to:
http://localhost/Create.php?levelName=PHPTest&levelAuthor=Test3&levelData=[snip]
I expected to see something along the lines of "(SUC)|ID:4" (there were 3 entries in the database at the time), but I saw this:
(SUC)|ID:4(SUC)|ID:5(SUC)|ID:6(SUC)|ID:7(SUC)|ID:8(SUC)|ID:9(SUC)|ID:10(SUC)|ID:11
This was unexpected. I thought it was just an error in my code (keep in mind, the last one had a broken ID grabbing system, but worked), and that it would work, but then, I went to check the database, and saw a ton of duplicates with the same data.
Does anyone know how to fix this code?
Obvious question but autocommit is enabled on database?
Do you have some open transaction?
Use this to check open transactions on MySQL.

Echoing Out A Mysql Query

Alright. I have searched and searched for an answer, but I just could not find it.
I am writing a simple php script that takes the url information and runs it through a MySQL query to see if a result comes up. I try to echo the variable holding the query out, but nothing shows up. I know there must be a result because if I enter the query manually in MySQL it displays my desired result.
$result = mysqli_query("SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
I have tried to echo out both the $result and $data. But there is nothing displayed. I am so new to programming, and this is my first StackOverflow post, so forgive me if I am making huge errors.
Actually mysqli_query() requires two parameters... check the following sample example ..
<?php
$conn = mysqli_connect('localhost','root','','your_test_db');
$_GET['page'] = 1;
$result = mysqli_query($conn,"SELECT * FROM your_table WHERE id = '" . $_GET['page'] . "'");
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
?>
As you have stated you are just in a learning phase, it is okay to code these sort of queries just to learn yourself but do not code these kind of queries as these queries are vulnerable so i would suggest you to use prepare queries or PDO...
Also never use SELECT * in your queries, this is a bad practice, only deal with the fields which you requires in return.
Also, you can always check whether your database is connected or not. So that you have a better idea.
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
you have not mentioned whether you are following OOP structure or not .. so i would suggest you to check error_reporting() and connect database on the same page to check the things around ..
Also you can check whether you without WHERE condition for now "SELECT * FROM your_table just to make sure whether you are getting atleast all the records or not.
The problem is that you're not setting up the connection in the query. mysqli_query() requires two parameters.
Make the connection first:
$conn = mysqli_connect("localhost", "user", "password", "dbname");
Now execute the query:
$result = mysqli_query($conn,"SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
NOTE: Your code is heavily vulnerable to MySQL injections. Use MySQLi or PDO Prepared statements.
Also, you should use mysqli_errno() to find out your query bugs.
Edit:
Also do this:
while($row=mysqli_fetch_assoc($result)){
//do the result output.
}

i am currently have an MYSQL syntax error

i am very new at MYSQL and after i created this script to update a row in the table of a MYSQL Database and run it i get this error
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '265'', Employer_VAT_number = ''45698'', Employer_Name = ''Namtax_Ltd'', Employer' at line 3
here is the code
// username and password sent from form
$Numb=$_POST["Numb"];
$VAT=$_POST["VAT"];
$Name=$_POST["Name"];
$Addr=$_POST["Addr"];
$PO=$_POST["PO"];
// To protect MySQL injection (more detail about MySQL injection )
$Numb = stripslashes($Numb);
$VAT = stripslashes($VAT) ;
$Name = stripslashes($Name) ;
$Addr = stripslashes($Addr) ;
$PO = stripslashes($PO) ;
$Numb = "'" . mysql_real_escape_string($Numb) . "'";
$VAT = "'" . mysql_real_escape_string($VAT) . "'";
$Name = "'" . mysql_real_escape_string($Name) . "'";
$Addr = "'" . mysql_real_escape_string($Addr) . "'";
$PO = "'" . mysql_real_escape_string($PO) . "'";
$sql=("UPDATE $tb1_name SET Employer_Registration_Number ='".$Numb."', Employer_VAT_number = '".$VAT."', Employer_Name = '".$Name."', Employer_Address = '".$Addr."', Employer_Postal_Address = '".$PO."' WHERE Employer_Name = '".$Name."' ");
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Successfully Updated";
mysqli_close($con);
?>
</body>
This here:
$Numb = "'" . mysql_real_escape_string($Numb) . "'";
Firstly, that isn't proper syntax and you're using mysqli_ to connect with, least I sure hope you are.
Those different MySQL APIs do not intermix with each other.
That should read as:
$Numb = mysqli_real_escape_string($con,$Numb);
while doing the same for the rest of your variables, following the same method outlined here.
Footnotes:
Seeing you didn't post what $tb1_name is, doubt that would be causing an issue. But just for the sake of argument, wrap that variable in ticks, just so if your table name changes to something containing a hyphen or a space, or anything that MySQL will complain about.
UPDATE `$tb1_name` SET...
Plus, since you didn't mention which MySQL API you're using to connect with, make sure it is in fact mysqli_ and not mysql_ or PDO.
It doesn't look like it, but I have to be 100% sure.
Your connection should resemble something like this:
$con = mysqli_connect("yourhost","user","pass","your_DB")
or die("Error " . mysqli_error($con));
Again, those different MySQL APIs do not intermix with each other.
Consult (PHP: Choosing an API - Manual): https://php.net/mysqlinfo.api.choosing
"I am very new at MYSQL..."
Seeing you're new to this:
Use mysqli with prepared statements, or PDO with prepared statements.
Additional notes. (as an edit)
I noticed another question you posted earlier:
https://stackoverflow.com/q/30191388/
where you said "Thank you it worked " in the answer given https://stackoverflow.com/a/30191647/
I don't get that.
How could that possibly work where you're using if (!mysqli_query($con,$sql))?
You'll need to show us the way you're connecting with here.
If you truly want to see if your query was successful, use mysqli_affected_rows().
if(mysqli_affected_rows($con)){
echo "Successfully updated.";
}
else{
echo "Not updated.";
}
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.

Avoiding \r\n in SQL query PHP/PDO

I have a problem. I'm trying to update a mysql table with data grabbed. The problem is there is an invisible \r\n on the end and it's not functioning properly.
DELETE FROM `tracker`.`gains` WHERE `gains`.`runescape_name` = 'Andy FFS\r\n';
DELETE FROM `tracker`.`gains` WHERE `gains`.`runescape_name` = 'Cancerbear\r\n';
DELETE FROM `tracker`.`gains` WHERE `gains`.`runescape_name` = 'Pandora25';
DELETE FROM `tracker`.`gains` WHERE `gains`.`runescape_name` = 'Pether\r\n';
I have a file called memberlist and update.php loops through each line in memberlist.txt and inserts or updates the columns in the table. If you look at the above query (that is just me trouble shooting) I don't actually want to delete it's just to show you the \r\n at the end. It's bringing back 0 in all columns except for the name pandora25 (which happens to be at the bottom of memberlist.txt. What I don't understand is I have a php script to edit memberlist.txt on my website, and that's when the problem occurs. But say I open memberlist.txt via SFTP and upload it to my website, it works correctly. So maybe it's something to do with the editing of the txt file with php and it's adding and invisible \r\n at the end I'm not sure. But I have studied quite a bit on this issue and I've looked that you can insert into a MySQL table with ->prepare in PDO (I don't use mysqli).
I believe the loop variable [$k] plays an important role in this problem. Here is my code that I seem to be having a problem with:
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tracker';
$userdb = 'root';
$passdb = 'password';
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Query
$sqlquery = ("
INSERT IGNORE INTO
gains (runescape_name, hitpoints_starting_exp, magic_starting_exp, range_starting_exp)
VALUES
('" . htmlspecialchars($name[$k]) . "', '" . $hitpointsexp . "', '" . $magicexp . "', '" . $rangedexp . "')
ON DUPLICATE KEY UPDATE
hitpoints_starting_exp='" . $hitpointsexp . "', magic_starting_exp='" . $magicexp . "', range_starting_exp='" . $rangedexp . "'");
if($conn->exec($sqlquery) !== false) echo 'completed'; // If the result is not false, display confirmation
$conn = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
The purpose of this script is to use start.php to insert the current grabbed data into hitpoints_starting_exp, magic_starting_exp and range_starting_exp. I then run stop.php which is a similar script and insert the data grabbed there into hitpoints_end_exp, magic_end_exp and range_end_exp. I then echo a table on index.php which calculates the difference between the two columns.

Categories