I seem to be missing something quite fundamental here and yet my code doesn't seem to be any different to any of the numerous online tutorials that I have looked at.
What I would like is for someone to look at this and say....Oh you have forgotten to...etc;
This is what I have on a separate update page which is intended to perform the update then cycle back to the main admin page:
require_once('../Connections/MyConn.php');
$sql_statement = "UPDATE skyscrapers SET ";
$sql_image = "Ad_image = '" . $_REQUEST['image'] . "', ";
$sql_expire = "Ad_Expires = '" . $_REQUEST['expire'] . "'";
$result = mysql_query($sql_statement . $sql_image . $sql_expire . " WHERE Ad_ID=" . $_REQUEST['ADID']);
if (!$result) {
echo("<p>Error performing query: " . mysql_error() . "</p>");
exit();
}
mysql_close ($MyConn);
header("location:Admin_skyscrapers.php");
However when I run this I get the following error:-
"Error performing query: No database selected"
Well, haven't I selected the database in the connection script which already works everywhere else?
I realise the code isn't very pretty and I am being naughty using the url to pass variables at the moment - I do promise to change this when I get it to work :)
So, any pointers would be helpful, thanks in advance.
Edit to add...
This is the connection script with the sensitive stuff redacted:-
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_MyConn = "*************.co.uk";
$database_MyConn = "db**********";
$username_MyConn = "dbo*********";
$password_MyConn = "*****";
$MyConn = mysql_pconnect($hostname_MyConn, $username_MyConn, $password_MyConn) or trigger_error(mysql_error(),E_USER_ERROR);
This may or may not be declared in your MyConn.php but all you need is a line:
mysql_select_db($db_name);
Where $db_name is the name of your database.
This should come before you attempt to execute the query.
For DB select you have to add mysql_select_db(DatabaseName); or
$dbconn=mysql_select_db($dbname,$MyConn);in MyConn.php
For update in Database you have to use connection variable which is in MyConn.php i.e.$MyConn as follows
$result = mysql_query($sql_statement . $sql_image . $sql_expire . " WHERE Ad_ID=" . $_REQUEST['ADID'],$MyConn);
or
$result = mysql_query($sql_statement . $sql_image . $sql_expire . " WHERE Ad_ID=" . $_REQUEST['ADID'],$dbconn);
respectively
Hope It Helps!!!!!!!
Related
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.
It's pretty much one of my first times working with MYSQL, and I can't seem to fix this one error I keep getting. I'm trying to store data to a table which has an auto_increment on its id (first column).
The error I keep getting is this:
"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 'voorletters ='asd', tussenvoegsel ='', achternaam ='', roepnaam ='', adres ='', ' at line 1"
I just filled the textboxes with a little bit of rubish, there are no columns that require data either. Here is the code I use:
if(isset($_POST['save']))
{
$voorletters = $_POST['voorletters'];
$tussenvoegsel = $_POST['tussenvoegsel'];
$achternaam = $_POST['achternaam'];
$roepnaam = $_POST['roepnaam'];
$adres = $_POST['adres'];
$postcode = $_POST['postcode'];
$plaats = $_POST['plaats'];
$geslacht = $_POST['geslacht'];
$emailadres = $_POST['emailadres'];
$telefoonnummer = $_POST['telefoonnummer'];
$mobielenummer = $_POST['mobielenummer'];
$geboortedatum = $_POST['geboortedatum'];
$bsn = $_POST['bsn'];
mysql_query("INSERT INTO `naw` "
. "voorletters ='$voorletters', "
. "tussenvoegsel ='$tussenvoegsel', "
. "achternaam ='$achternaam', "
. "roepnaam ='$roepnaam', "
. "adres ='$adres', "
. "postcode ='$postcode', "
. "plaats ='$plaats', "
. "geslacht ='$geslacht', "
. "emailadres ='$emailadres', "
. "telefoonnummer ='$telefoonnummer', "
. "mobielenummer ='$mobielenummer', "
. "geboortedatum ='$geboortedatum', "
. "bsn ='$bsn' "
. "WHERE id = '$id'")
or die(mysql_error());
If this isn't enough information, please tell me. I've tried a lot of things, but I can't seem to figure it out.
You mix up insert and update syntax. Replace
INSERT INTO `naw` voorletters ='$voorletters'...
with
UPDATE `naw` set voorletters ='$voorletters'....
And you should really use Prepared Statements to avoid syntax errors and SQL injections due to user input.
You have a wrong syntax
The INSERT syntax is
INSERT INTO `YourTableName`(`Field1`, `Field2`, `Field3`, `Field4)
VALUES ('value-1','value-2','value-3','value-4')
The UPDATE syntax is
UPDATE `YourTableName`
SET `Field1`='value-1',`Field2`='value-2',`Field3`='value-3',`Field4`='value-4'
WHERE YourConditions
Just use following code. Make sure that you are inserting data for every field sequentially-
mysql_query("INSERT INTO `naw` VALUES(
'".$voorletters."',
'".$tussenvoegsel."',
'".$achternaam."',
'".$roepnaam."',
'".$adres."',
'".$postcode."',
'".$plaats."',
'".$geslacht."',
'".$emailadres."',
'".$telefoonnummer."',
'".$mobielenummer."',
'".$geboortedatum."',
'".$bsn."')")
or die(mysql_error());
You should remove the `` around naw, it's ok in phpmyadmin but quite messy almost every where else.
And you souldn't concatenate every line, do it in one "..." and use backspace to make it more readable.
So:
mysql_query("INSERT INTO naw
VALUES('$voorletters',
'$tussenvoegsel',
... ,
WHERE id = '$id'");//you can't do that, maybe you should use an UPDATE
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.
trying to get my head around this MySQL jibberish, lol - now I do not normally ask for help but on this one I think I do need a shove.
I have searched for the answers to this however the solutions are all based around the askers duplication of the fetch_array command, however I have not done this but still this code skips the first entry.
Can someone point out what I have done here that causes this to skip...?
code:
$link = mysqli_connect('localhost','person','password', 'database'); // connect to database
if (!$link) { die('Could not connect to MySQL: ' . mysqli_connect_error()); } // problem, then die
$sql = "SELECT * FROM id_info_db"; // Query construct
$result = mysqli_query($link, $sql); //query action
while ( $row = mysqli_fetch_array($result) ) { // print out rows
echo "User: " . $row["username"]. " - Password: " . $row["password"]. " " . $row["email"]. "<br>"; }
mysqli_close($link);
For some reason I had a loose /body tag at the end? why I don't know but it generated this result. Now I have deleted it the output is correct.
A remnant that should have been deleted that throws up an unfathomable error. Lol
If i try this is doesn't work:
<?php
include ($_SERVER['DOCUMENT_ROOT'] . '/contact/config.inc.php');
$hash = hash('md5', $_POST["password"]);
$connection = mysql_connect($host, $user, $password);
mysql_select_db($database, $connection);
mysql_query("UPDATE data
SET password=" . $hash .
"WHERE id=" . $_POST["id"]);
mysql_close($connection);
?>
The data just won't show up in the database. I tried setting the hash and id to a fixed value, still didn't work. I am sure the database connection works, as it works in other scripts. And all variables show up correctly when i echo them.
I'm new to PHP and MySQL.
Try adding quotes surrounding the values,
mysql_query("UPDATE data SET password='" . $hash . "' WHERE id='" . $_POST["id"] . "'") ;
Note: Mysql extensions are deprecated. Please use Mysqli_* or PDO extensions.
The reason why, is because you are escaping your query incorrectly, you are missing the quotes around your variables.
Change this:
mysql_query("UPDATE data
SET password=" . $hash .
"WHERE id=" . $_POST["id"]);
To This:
mysql_query("UPDATE data
SET password='" . $hash .
"' WHERE id='" . $_POST["id"] ."'");
and whilst typing this, I noticed you did not go back into your query to close your escape.
Notice I have added quotes and went back into the query to close the quotes.