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.
Related
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
im trying to update date on the table. YYYY-MM-DD HH-MM-SS.
There is the code i have.
It takes information from table and after that I want it to set date in that table to current time
<?php
$username = "root";
$password = "sawasq";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
$code = $_POST['kodas'];
$code = stripslashes($code);
$sql = mysql_query("SELECT * FROM dviraciai WHERE ID='$code'");
$Pavadinimas = 'Pavadinimas';
$Metai = 'Metai';
$Status = 'Status';
$rows = mysql_fetch_assoc($sql);
echo 'Pavadinimas: ' . $rows[$Pavadinimas] . '<br>';
echo 'Metai: ' . $rows[$Metai] . '<br>';
echo 'Status: ' . $rows[$Status] . '<br>';
$sql2 = mysql_query("UPDATE Dviraciai WHERE ID='$code' SET date=CONCAT(CURDATE(),' ',time(mytime))");
mysql_close();
?>
I get $code from input.
Dviraciai is my table.
I dont get any error. But when i enter my $code it shows the info but doesnt change time in table after I restart phpMyAdmin
Your query is totally wrong, and since you never bother checking for errors and simply ASSUME nothing could ever go wrong...
Update syntax is
UPDATE ... SET ... WHERE...
You have the set/where reversed. And note that restarting phpmyadmin is beyond pointless. It's a MANAGEMENT INTERFACE. It's not the database itself. It's like trying to change the outcome of a tv show by turning your tv on/off.... the show's going to end up broadcasting the same ending no matter what you to do with your TV.
Never assume success with DB operations. Even if your SQL is 100% syntactically perfect (and yours definitely isn't), there's far too many OTHER reasons for a query to fail. Assuming success is, frankly, just plain stupid. Always assume failure, check for failure, and treat success as a pleasant surprise. At bare minimum, have something like this:
$result = mysql_query(...) or die(mysql_error());
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 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.
We have a website that accesses a SQL Server 2005 server for one query. Currently, the site is in ASP, we are moving it to PHP, and the PHP one is currently being tested. After we run a few successful queries on the PHP site, it returns the "Error in database query. Please try again later" line in the code below. When I rewrote that line with sqlsrv_errors to elaborate, it told me that the table didn't exist. There are about 40 tables in the database, but after the error happens it only shows 8 of them in Management Studio. However, if I allow it to sit for about 5 minutes, all of the tables are restored. No matter how many times the old ASP site is used, the table does not do this. However, when the tables disappear from using the new site, the old site shows inaccessible for a few minutes until the tables re-appear in SQL Server management studio. I didn't see any kind of connection limits on the SQL Server, so I don't know whether it's something I'm doing in the PHP SQL queries or within the SQL Server properties.
<?php
include ("dbvals.inc.php");
if (!empty($_POST['lastnamebox'])) {
$dbhandle = sqlsrv_connect($dbServer, $connectioninfo);
if($dbhandle == false){
echo "Error connecting to database. Please try again later. ";
}
else{
$query = "SELECT * FROM Person WHERE LastName LIKE '%' + ? +
'%' AND InactiveFlag = 'N' ORDER BY LastName, FirstName";
$params = array();
array_push ($params, $_POST['lastnamebox']);
$results = sqlsrv_query($dbhandle, $query, $params);
if($results == false){
echo "Error in database query. Please try again later.";
//This is printed when database tables temporarily disappear
}
else
{
$row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC);
if($row){
do{
echo "<tr><td class='tablecell'>";
echo $row['LastName'] . "," . $row['FirstName'] . "<br>";
echo "Address: " . $row['Address'] . "<br>";
echo "City, State, Zip: " . $row['CSZ'] . "<br>";
echo "</tr></td'>";
}while($row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC));
}
else{
echo "No results found. Please try another query.";
}
}
}
sqlsrv_free_stmt($results);
sqlsrv_close($dbhandle);
}
else {
echo "Please type a value in the search box.";
}
?>
The $query is wrong to begin with. Change it to:
$query = "SELECT * FROM Person WHERE LastName LIKE '%' + ? +
'%' AND InactiveFlag = 'N' ORDER BY LastName, FirstName";
Not sure about the tables disappearing though. What driver are you using?
Just another issue I'm seeing with the code not sure if it's related to your problem. or another copy error but here it is.
if ($r1 = sqlsrv_fetch_array($results)) {
while( $row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC)){
The first fetch should also have '($results,, SQLSRV_FETCH_ASSOC)'
Additional that check is going to eat the first returned record which may or may NOT be what you intended.
Also it is possibly that PHP seeing some results in the while as false even though they aren't and the server is still waiting on you to finish getting the rest. Seen code like that cause 'Server has got away' errors in MySQL which could be what is going on here as well.
Not sure of the syntax but a sqlsrv_clode_cursor() just before the connection close might also fix your issue if there's some kind of connection polling going on. Could be simply running out of connection or getting old one in a incorrect state.
SELECT * FROM Person WHERE AND LastName LIKE
Looks like there something missing between the WHERE and AND to me.
I don't know SQL Server really so it could allow that but it's not standard SQL. Depending on how it's reacting to that error I could see it 'Going away' so to say and reporting tables missing.