I am experiencing something so basic, yet so annoying that I thought I had to put it out to the wider community to save my sanity.
I am using a table within a database to store some very basic data. There is only two columns, Id and Campaign. I only want to use a single row of the table, however, campaign will be updated at various points. I have set up the table as follows:
$sql = "CREATE TABLE IF NOT EXISTS TestCampaign(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
Campaign CHAR(20))";
Initially I write to the table to insert a null CHAR in campaign:
$sql = "INSERT INTO TestCampaign (Campaign) VALUES ('None')";
The based on a specific text field being filled in on an html form followed by a submit button press I intended to do the update of the campaign field:
$sql = "UPDATE TestCampaign SET Campaign = '$Test' WHERE id = '1'";
$Test is the POSTED campaign name from the form. Unfortunately although the INSERT works fine the UPDATE doesn't. I have checked the permissions and I have ALL on this database. I have also checked the syntax with various sites and it seems that it is fine.
Interestingly I do not get an error when I echo:
echo " ".mysqli_error($con);
I'm sure I have made some basic error somewhere but I have been looking at it for so long and changing the syntax that I can't seem to spot it.
Any help would be appreciated.
UPDATE:
I have played around with the code and it seems as though the UPDATE code does work, however, It only works when it is the next line of code after the INSERT. In fact I have found that it works as long as it is not where I need it to be. I have it placed in 'if' statement that is run only on a specific button press on the form:
if(isset($_POST['TestID']))
{
Some Code;
$sql = "UPDATE TestCampaign SET Campaign = '$Test' WHERE id = '1'";
Some More Code;
}
I have checked the rest of the code in the 'if' statement and it seems solid.
Is this odd behaviour or have I missed something?
SOLVED
Finally found out what the problem was, it ended up that when exiting the first 'if' statement as expected the html form code was revisited which must have closed the connection to the database, when the button was pressed to run the second 'if' statement there was a connection to MySQL but no connection to the database I needed access to. A quick fix to re-connect and all works fine.
$sql = "UPDATE TestCampaign SET Campaign = '$Test' WHERE id = 1";
Is the only thing I think is wrong... What do you get with :
Select * from TestCampaign
have you set up any triggers based on this table name? After update, before update triggers may prevent you from storing the required data on the table.
Also, MySQL may use 0 as id value if you don't specify the value of the id at sending insert command. Are you sure the value of your id is 1 in the record you want to update? If you have run insert statements before on your table, the id may be a larger number than 1, because of the MySQL indices (I guess this may be the problem).
I don't know how exactly PHP statements are processed when sending them to MySQL, but I would recommend you to use PDO statements, the PHP syntax would look something like this:
$sql = $pdo->prepare("UPDATE TestCampaign SET Campaign = ? WHERE id = ?");
$sql->bindParam(1, $Test);
$sql->bindParam(2, 1);
$sql->execute();
Tutorial: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
I would also echo your $Test variable to check what is stored in it.
Hope it helps...
Finally found out what the problem was, it ended up that when exiting the first 'if' statement as expected the html form code was revisited which must have closed the connection to the database, when the button was pressed to run the second 'if' statement there was a connection to MySQL but no connection to the database I needed access to. A quick fix to re-connect and all works fine.
Related
I have come across many questions and answers related to this kind of questions, but not for exactly this question.
Well, according to the official MYSQL documentation it says
If you set a column to the value it currently has, MySQL notices this
and does not update it.
But practically, when I update a same value to a MYSQL column, the query successfully executing and displaying "Your query has been successfully executed ".
So How do I exactly know that the query hasn't updated, when I update a column with the same value?
Also Is it possible to get an error message to the client (browser), when I try to update a same value, from the browser via a submit form to the MYSQL server via a backend language like PHP?
When updating a Mysql table with identical values nothing's really affected so rowCount will return 0.
Just create your PDO object with
<?php
$p = new PDO($dsn, $user, $password, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
?>
and rowCount() will tell you how many rows your update-query actually found/matched.
Check this link also.
you may use like to avoid updating same value
UPDATE users
SET first_name = 'Michael'
WHERE id = 123
AND first_name IS DISTINCT FROM 'Michael';
I have a problem when calling execute on a prepared statement using PDO.
Here is my code:
$db = Connection::getConnection();
$query = 'INSERT INTO stories (st_title, st_authors, st_content, st_cover) VALUES (?,?,?,?)';
$params = ['title', 'Authors', 'content', 'cover'];
$stmt = $db->prepare($query);
echo "before <br>";
$stmt->execute($params);
echo "after <br>";
If I comment out the line $stmt->execute($params);, both "before" and "after" show up. However, if I leave it uncommented, neither of them show up.
I have also tried using bindParam() instead of executing with an array, but I got the same result.
It's also worth taking note that inserting into the database, with the exact same parameters, from sqlPlus works flawlessly.
I am running an oracle 11g database server locally.
Any help would be highly appreciated, I've been stuck on this for a while now.
Edit: I mentioned it in the title, but forgot to mention it here too. When this code runs, the server hangs indefinetely and I am forced to restart apache.
Edit2: The connection is ok, and I figured out the source of the problem.
On the stories table, i have an unique constraint on st_title.
The problem occurs when i try to insert a story with the same title as a previous one AFTER that previous one has been DELETED.
If I remove the unique constraint, the problem goes away.
However I would like to keep that constraint. Any ideas as to what could cause this?
Edit3: The triggers I have on the stories table:
--auto-increment on st_id--
DROP SEQUENCE stories_id_seq;
CREATE SEQUENCE stories_id_seq;
CREATE OR REPLACE TRIGGER stories_id_auto_inc
BEFORE INSERT ON stories
FOR EACH ROW
BEGIN
SELECT stories_id_seq.NEXTVAL
INTO :new.st_id
FROM dual;
END;
/
--auto-completion for st_date_added--
CREATE OR REPLACE TRIGGER stories_date_added
BEFORE INSERT ON stories
FOR EACH ROW
BEGIN
SELECT sysdate
INTO :new.st_date_added
FROM dual;
END;
/
CREATE OR REPLACE TRIGGER stories_delete
BEFORE DELETE
ON stories
FOR EACH ROW
DECLARE
BEGIN
DELETE FROM st_cat
WHERE st_id = :old.st_id;
-- DELETE FROM characters
-- WHERE st_id = :old.st_id;
DELETE FROM favourites
WHERE st_id = :old.st_id;
DELETE FROM bookmarks
WHERE st_id = :old.st_id;
DELETE FROM comments
WHERE st_id = :old.st_id;
DELETE FROM ratings
WHERE st_id = :old.st_id;
END;
/
The last one is the only relevant one, I think, but i posted them all, just in case.
It's worth noting that the problem only occurs with PDO. If i do the same operations from sqlplus, it works fine.
SOLVED: As it turns out, it wasn't a problem with my code, it was simply the fact that I didn't do a commit; in sqlplus after deleting the rows, and PDO dis weird things with them. (It didn't just show me the normal "title is already taken" message, which is what fooled me).
Probably your Database Connection is not setup correctly.
Take a look at this post to check if your connection is stable and you can succesful perform queries to it.
PDO Connection Test
I am having problems updating and inserting data into my database. I have debugged most of the program so I know for sure that the problem is the line of code for updating and the line of code for inserting data. I am very confused because their are other functions that use the same code and all the variables I used in each function were declared locally in the function so I know they are not conflicting. the code at the top that says
is all the database code to open the line of communication with the database and php. That code works I've already tested it in other programs. I can still pull data with the SELECT code from the database and I've checked and double checked if the names match up with the table. This code is part of some ajax code so it will update in real time but the post I use with the javascript transfers the data just fine to the php file. So I have no idea what I'm doing wrong or if there is just something wrong with the server. If anyone as any ideas please let me know. Also the purpose of this code is to make it so that users can like, favorite, and give a rating out of 5 stars to the content they are viewing on my site.
This is the code:
<?php include "base.php";?>
</head>
<?php
$rateMe = mysql_query("SELECT * FROM rating WHERE Username = '".$_SESSION['Username']."' AND Title = '".$_POST['myTitle']."'");
if(mysql_num_rows($rateMe) == 0)
{
$registerquery = mysql_query("INSERT INTO rating (Username, Author, Star, Like, Favorite, Title) VALUES('".$_SESSION['Username']."','".$_POST['myAuthor']."','".$_POST['myrating']."','".$_POST['myLike']."', '".$_POST['myFavorite']."', '".$_POST['myTitle']."')");
}else
{
$makeUpdate = mysql_query("UPDATE rating SET Star = '".$_POST['myrating']."' WHERE Username = '".$_SESSION['Username']."' AND Title = '".$_POST['myTitle']."'");
}
?>
and this is the table I'm trying to insert data into
table: rating
Username varchar(255)
Author varchar(255)
Star float
Like varchar(255)
Favorite varchar(255)
Title varchar(255)
Here is what your insert query will probably be like when you print it
INSERT INTO rating (Username, Author, Star, Like, Favorite, Title) VALUES('John','Jim','xx','xx', 'xx', 'xx')
The like keyword in the insert statement will probably throw an error like below
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 'like) values('John'
Check your update if it's working
As Markus intimated, your code is extremely vulnerable to SQL injection attacks. Further, the PHP manual strongly recommends using the mysqli extension, over the mysql extension.
I would suggest you take a moment to read through this article on PDO, prepared statements and the right way to INSERT/UPDATE data into your model.
I have values which use the GET method to send URL variables to a PHP page using Ajax.
On the page, I have:
$value=$_GET["q"];
$id=$_GET["id"];
$mod=$_GET["mod"];
I started out using the UPDATE SET method to modify values in a mySQL database.
I used: $num_rows= mysql_num_rows($result);
With an If Else statement to either Insert the values (if not there) or Update the column "Attribute"
But this was very inconsistant and often would not UPDATE, and there developed several duplicate values (even though if($num_rows > 0){ (WHERE Object_ID = '".$mod."' AND Type='".$id."') it SHOULD NOT have inserted, but it did.)
So I switched to this:
$sql="SELECT * FROM Attributes WHERE Object_ID = '".$mod."' AND Type='".$id."'";
$result = mysql_query($sql);
mysql_query("DELETE FROM Attributes WHERE Object_ID = '".$mod."' AND Type = '".$id."'");
mysql_query("INSERT INTO Attributes (Object_ID, Type, Attribute)
VALUES ('".$mod."', '".$id."', '".$value."')");
I know, really bad idea. But Even this method doesn't always insert the values correctly.
I know that the variables are getting to the page, because the response would be written in a div using innerHTML, and it always showed up correctly.
How can I ensure that the values are ALWAYS updated/inserted in the database?
Why not run a SELECT COUNT(*) for the condition and check what that returns and based on that run your UPDATE or INSERT?
i am really confused what is wrong with your database operation but the only way to ensure is to send back response from your php script to ajax.
It can be json or simple text informing you that which action was requested and what is performed. Depending on the response you can adjust what you want.
You have to query the table to find out if the id already exists there or not if it exits then write an Update Query i.e.
$update = "update tbl_name set column=value where id = $_GET['id']"
and if the id does not exist then use the insert
$insert = "Insert into ......"
hope this solves your issue. And Further more you have to echo out the response here in either a string format or a some other value which you will get in the success method of $.Ajax.
No need to query the database to see if the data exists already. As long as you have good data, you can delete the row every time. If the row doesn't exist, the DELETE does nothing.
Run these two queries every time, and you will be fine.
mysql_query("DELETE FROM Attributes WHERE Object_ID = '$mod' AND Type='$id'");
mysql_query("INSERT INTO Attributes (Object_ID, Type, Attribute) VALUES ('$mod', '$id', '$value'");
And please at a minimum, before you do anything with $_GET, run those through mysql_real_escape_string first. You should probably be doing more checking just to make sure that the values passed in are valid.
$value=mysql_real_escape_string($_GET["q"]);
$id=mysql_real_escape_string($_GET["id"]);
$mod=mysql_real_escape_string($_GET["mod"]);
Ok, let say we have two rows:
member_id, name
Let say member_id = 15 and name = 'John';
I want to UPDATE this data and do the following query:
mysql_query("UPDATE members SET member_id = 14, name = 'Peter' WHERE member_id = 15
This is just an example, but is it possible that mysql would fail and UPDATE for example only name row. So, after completing mysql_query above, it would become member_id = 15 and name = 'Peter';
It is just an example. Today, a similar situation happened in my website and I checked my code hundred times and I see no errors and there hadn't been no same errors before it at all.
So, should I recheck my code one hundred times more, or it can happen?
Thank you very much.
According to the spec, single UPDATE statements are atomic; ie: either it updates all columns or it doesn't update any of them.
So no, it shouldn't happen. But of course there could be a bug with MySQL.
Put or die(mysql_error()); after your query so that if this really is happening then you would at least know about it.
I think it should not happen that it would become member_id = 15 and name = 'Peter'. The SQL syntax is right as far as i can see and it seems all good. If something wrong happens to your database and your query is executed in that moment God only knows what could happen. Despite this, most of the time either the query is executed entirely or it is not, making mysql_query() return false.
You should, as already suggested at least check if there where any error with a code such as the following if you are in an online business website:
mysql_query($sql) or die('An error occurred');
or something like as follows if you are in debug mode:
mysql_query($sql) or die(mysql_error());
I'm not as sure as everyone else that single-row updates are atomic. MySQL differs from standard SQL in that it does the column assignments of a single-table UPDATE left-to-right. That means member_id = 14 is done before name = 'Peter'. If name = 'Peter' violates a constraint, or triggers another update that fails, then that assignment will fail. However, whether the statement as a whole fails or not may depend on various factors, including whether the table is using a transaction-safe engine.