I am getting this weird problem where a MySQL insert is happening twice. I kept pairing down the code until I had the simplest version, but it's still happening. Has anyone seen this before? This is on a Tomcat server.
Below is my super-simplified code. When I run this, two entries appear in the table withe same value. The strange thing is it seems to run the whole page twice, because if I do a select quickly enough I can see the first entry by itself, then seconds later the second entry appears. When I timestamp the rows, they are 1-ish seconds different.
"jdbc:mysql://127.0.0.1/mydatabase",
"myusername",
"mypassword"
);
java.sql.Statement statement = connection.createStatement();;
statement.execute("INSERT INTO tbl_test (Value) VALUES ('Test value')");
%>
Additional info:
Also if I execute a select statement after the insert and select the complete contents of the table, only the first entry shows up. But when I look in the database, there are two entires. So it's like the whole jsp page finishes running, then runs again silently in the background.
Here is an expanded version of the code that allows you to choose the input value for the database, so you can try this out on the fly and see what's happening:
<%
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection connection = java.sql.DriverManager.getConnection(
"jdbc:mysql://***/***",
"***",
"***!"
);
java.sql.Statement statement = connection.createStatement();
String Value = request.getParameter("Value");
statement.execute("INSERT INTO tbl_test (Value) VALUES ('" + Value + "');");
java.sql.ResultSet rs = statement.executeQuery("SELECT * FROM tbl_test;");
while (rs.next()) {
%><%=rs.getString("ID")%>=<%=rs.getString("Value")%><BR><%
}
%>
You can try out this code at:
http://familychurch.life/familychurch/test.jsp?Value=Whatever
(Replace "Whatever" with the value you want to insert.)
Run it once and you'll see the value inserted once. But run it a second time, and you will see that the value you entered before is now in the table twice.
It turns out the problem was caused by a Chrome extension (Video Downloader for FaceBookâ˘). It must have been reloading the page silently in the background.
Special shout-out to #RiggsFolly for helping me figure it out!
Related
I am wanting to take data from mysql, display it, have users edit this data and then save it to the database. I have all currently working except the saving to the database part. I have been lead to believe that the UPDATE query in mysql is how you get this to work. I put an UPDATE query in place and had no luck. Has anyone here experienced this issue before? I have read several posts here and on perl monks about this issue and can't seem to find an answer that solves my problem. I will put some of my code below. Thanks!
my $dbh=DBI->connect("dbi:mysql:survey_one", "user", "password", { PrintError =>0, RaiseError => 1, AutoCommit => 1}) or die $DBI::errstr;
my $edit_sql = q{UPDATE new_survey SET question = ? WHERE title= ?};
my $sthe = $dbh->prepare($edit_sql);
$sthe->execute($questionedit, $marathon);
$sthe->finish();
I'd like to note that if I were to SET the question column to a string like 'does this work?' I would have success. It's when I try to use user input $questionedit, which is defined as
$questionedit = param('editquestion'); This is where users can edit the question field.
Thanks!
The following are the four possible outcomes:
Nothing happens because the code isn't executed.
An exception is thrown because an error occurred (and RaiseError => 1 was used). The exception will end up being printed to STDERR unless caught.
->execute returns the string 0E0 (which is true, but numifies to zero) because no rows were updated because the WHERE clause didn't match any rows.
->execute returns a positive number indicating the number of rows modified.
Determine which case is applicable, and you'll know how to move forward.
I have the following code attempting to truncate a table. The Joomla documentation makes me believe this will work, but it does not. What am I missing?
$db = JFactory::getDbo();
truncate_query = $db->getQuery(true);
//$truncate_query = 'TRUNCATE ' . $db->quoteName('#__mytable');
$truncate_query->truncateTable($db->quoteName('#__mytable'));
$db->setQuery($truncate_query);
echo $truncate_query;
exit();
If I use the line that is commented out to manually generate the SQL, it does work. The reason I am still looking to use the truncateTable function is that I am trying to include the truncation in a transaction. When I use the manual statement, the table is still truncated even if another part of the transaction fails, which is annoying since the other statements rely on data that is truncated, so if the table is emptied when it shouldn't be there is no data left to run the transaction again. Very annoying!
Here's how you call/execute your truncation query:
JFactory::getDbo()->truncateTable('#__mytable');
And now some more details...
Here is the method's code block in the Joomla source code:
public function truncateTable($table)
{
$this->setQuery('TRUNCATE TABLE ' . $this->quoteName($table));
$this->execute();
}
As you can see the truncateTable() method expects a tablename as a string for its sole parameter; you are offering a backtick-wrapped string -- but the method already offers the backtick-wrapping service. (Even if you strip your backticks off, your approach will not be successful.)
The setQuery() and execute() calls are already inside the method, so you don't need to create a new query object nor execute anything manually.
There is no return in the method, so the default null is returned -- ergo, your $truncate_query becomes null. When you try to execute(null), you get nothing -- not even an error message.
If you want to know how many rows were removed, you will need to run a SELECT query before hand to count the rows.
If you want to be sure that there are no remaining rows of data, you'll need to call a SELECT and check for zero rows of data.
Here is my answer (with different wording) on your JSX question.
I am trying to add new users to my database. For some reason while using the same exact statement in two different scripts and trying to debug, mysql inserts a blank row instead of the actual data if I try to run the query from the php script in which I need it to run from.
On the other hand, when I try to run that exact query in from a random php script, passing the same exact variables (using session variables) to the database, it inserts the data into the database as it should with no problems. I have not idea how to fix such a problem and have been trying for quite a while now. I would greatly appreciate any advice on what I could do to fix this problem.
$usr_email = $_SESSION['email'];
$usr_company_name = $_SESSION['compame'];
$usr_city = $_SESSION['city'];
$usr_state = $_SESSION['state'];
$usr_phone = $_SESSION['phone'];
$usr_password = $_SESSION['password'];
$usr_first = $_SESSION['first'];
$usr_last = $_SESSION['last'];
mysql_query("INSERT INTO users (id, email, compname, city, state, phone, password, first, last)
VALUES('','$usr_email','$usr_company_name','$usr_city','$usr_state','$usr_phone','$usr_password','$usr_first','$usr_last')",$conn);
Using CI for the first time and i'm smashing my head with this seemingly simple issue. My query wont insert the record.
In an attempt to debug a possible problem, the insert code has been simplified but i'm still getting no joy.
Essentially, i'm using;
$data = array('post_post' => $this->input->post('ask_question'));
$this->db->insert('posts', $data);
I'm getting no errors (although that possibly due to disabling them in config/database.php due to another CI related trauma :-$ )
Ive used
echo print $this->db->last_query();
to get the generated query, shown as below:
INSERT INTO `posts` (`post_post`) VALUES ('some text')
I have pasted this query into phpMyAdmin, it inserts no problem. Ive even tried using $this->db->query() to run the outputted query above 'manually' but again, the record will not insert.
The scheme of the DB table 'posts' is simply two columns, post_id & post_post.
Please, any pointers on whats going on here would be greatly appreciated...thanks
OK..Solved, after much a messing with CI.
Got it to work by setting persistant connection to false.
$db['default']['pconnect'] = FALSE;
sigh
Things generally look ok, everything you have said suggests that it should work. My first instinct would be to check that what you're inserting is compatible with your SQL field.
Just a cool CI feature; I'd suggest you take a look at the CI Database Transaction class. Transactions allow you to wrap your query/queries inside a transaction, which can be rolled back on failure, and can also make error handling easier:
$this->db->trans_start();
$this->db->query('INSERT INTO posts ...etc ');
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
// generate an error... or use the log_message() function to log your error
}
Alternatively, one thing you can do is put your Insert SQL statement into $this->db->query(your_query_here), instead of calling insert. There is a CI Query feature called Query Binding which will also auto-escape your passed data array.
Let me know how it goes, and hope this helps!
I am writing some non-web app helper, and came across a need for a synchronous query call.
Basically, within a loop I need to check the database to see if the value exists. If it doesn't then insert the value. Currently, with node-mysql I can only get it to work with a callback. Because of that, node.js treats the call as asynchronous and keeps processing my request before the query is finished. This is a big issue because in the end it could be inserting duplicates because they were in the queue.
Ideal Solution - doesn't work. Results is actually the object of client, and I can't find the actual results within. However this does make it synchronous.
results = client.query('SELECT COUNT(md5) as md5Count FROM table WHERE md5 = "' + md5 + '"')
The following does not work. Node.js treats it as asynchronous, and outerResult is still the object of client.
outerResult = client.query('SELECT COUNT(md5) as md5Count FROM board WHERE md5 = "' + md5 + '"', function selectCb(err, results, fields) {console.log(results);});
Any help is appreciated.
Basically, within a loop I need to check the database to see if the value exists. If it doesn't then insert the value.
This is a problem best served with SQL. You don't solve this problem by talking to the database repeatedly, you solve this problem by having SQL only insert where the index value doesn't already exist.
INSERT INTO mytable ( name, address )
SELECT #name, #address FROM DUAL
WHERE NOT EXISTS (SELECT * FROM mytable WHERE name = #name, address = #address)
This is a super simplified example, and not the most optimized. You can do the same thing here with sets of data, instead of record by record, if you like.
Basically, within a loop I need to
check the database to see if the value
exists. If it doesn't then insert the
value. Currently, with node-mysql I
can only get it to work with a
callback. Because of that, node.js
treats the call as asynchronous and
keeps processing my request before the
query is finished. This is a big issue
because in the end it could be
inserting duplicates because they were
in the queue.
There is an asynchronous solution, there always is.
basically your worried that duplicate entries could be entered.
I presume you have an array of data to loop through. Your problem is solved with _.uniq or some other filter solution.
So you simply call _.uniq(md5s).forEach(function() { })