I have never encountered an error like this before. I was using prepared statements when it stared and have tried everything to correct the problem including stripping the form down to it's bare components.
The following code, when executed, is creating a duplicate row.
$sql = "INSERT INTO inventory
VALUES ('','$stocknum','$year','$make','$model','$price','$body','$mile','$engine','$trans',
'$drive','$doors','$fuel','$vin','$des','$featured','$sale','$features','$safety','$airbags','$power',
'$exterior','$interior','','','','','')";
$insert = mysql_query($sql,$connection) or die(mysql_error());
$name = mysql_insert_id();
I can't wrap my head around why it would do this.
I had the same problem in a project while using and orm library to access to the database. Also tried tested with mysql directly
After almost one day testing in multiple browsers and getting diferente results, i've found out that the extensions that i used (Webug) for Chrome caused tha recall to the page. After disabling the extension, it worked
I've tested some extensions that caused that problem... In chrome: Webug.
Hope it helps
The insert statement is possibly getting called twice. Did you add logging to make sure this code is only running once? And did you search to make sure there's no other code to add inventory records anywhere else?
How many columns are in the inventory table? Is the second row an exact duplicate of the first? I don't know PHP's DB interface but I could envision a bug where, if you give it more fields than there are columns, it attempts to create multiple rows.
EDIT: A little research on the MySQL documentation finds:
INSERT statements that use VALUES
syntax can insert multiple rows. To do
this, include multiple lists of column
values, each enclosed within
parentheses and separated by commas.
Example:
INSERT INTO tbl_name (a,b,c)
VALUES(1,2,3),(4,5,6),(7,8,9);
The values list for each row must be
enclosed within parentheses. The
following statement is illegal because
the number of values in the list does
not match the number of column names:
INSERT INTO tbl_name (a,b,c)
VALUES(1,2,3,4,5,6,7,8,9);
Depending on the contents of your variables and how the PHP/MySQL driver handles those variables (direct text substition or ? placeholders) the statement being executed may not look like you expect. Try displaying the value of $sql before you execute it.
When you query the table afterwards, are you only selecting from this table or are you perhaps joining it to another table? If you have more than one child record in the joined table you will get multiple results.
Your code looks correct to me, unless there is something in the rest of the page I'm not seeing.
In the absence of any real clear conclusion on this my observation is that I think Red Element is on the right track when he states 'I think it has something to do with my web host as now every script that adds SQL data is doing the same thing'.
I had the problem outlined above and could not see what on earth caused this until I ran the same code on a different platform and it worked fine. I was originally testing in a localhost WAMP configuration but when I promoted the code to a real server, it worked no problem.
Therefore I suggest that if anyone else has the problem it is worth a try on a different server config.
I'd guess you have a problem with an .htaccess file which is making 2 requests to the same script. Log a message with a timestamp when you do your insert.
Related
I have a few nagging questions about creating tables:
If I use PHP to create a MySQL function to create a table, I know it works the first time (to create a database for usernames and passwords) but what about the following times when the database sees the code to "create table". It seems to ignore it on my virtual server, but I was just wondering if this is wrong. Does it keep trying to create a new table each time? Is it okay to leave that code in?
Another question I have is, let's say I go into PHPMyAdmin and add a column called "role" (to define the user's role). The sign in page will crash since I added a column in PHPMyAdmin, but if add the column using PHP/MySQL it is perfectly fine. Why is that?
CREATE TABLE is executed each time you run the function. It's better to replace the syntax with CREATE TABLE IF NOT EXISTS.
The keywords IF NOT EXISTS prevent an error from occurring if the
table exists.
If you does not add IF NOT EXISTS it will throw the error.
Reference: http://dev.mysql.com/doc/refman/5.7/en/create-table.html
Please post your code in question to help you with second query.
1.) It depends on the purpose of the table.
If you need to create tables dynamically then your code should check each time
if the table exists:
CREATE TABLE IF NOT EXISTS 'yourTable'
However if you create the table only ones, there is no need to check for existence over and over again, so the code to create these table(s) should execute one time only.
2.) You need to update the function that does the insert or read after adding a column via PHPMyAdmin. It's difficult to answer your second question as I don't know what your functions do.
Do not keep your CREATE TABLE ... statements in your PHP code so that they execute every single time on every single page load. It's unnecessary and error prone. The statements are not being ignored, very likely they are run and are producing errors, and you're simply not checking for errors.
Database creation is a deployment step, meaning when you upload your code to your server, that's the one and only time when you create or modify databases. There are entire toolchains available around managing this process; learn something about automated deployment processes and database schema versioning at some point.
No idea without seeing your code and the exact error message.
I have 2 sql servers on 2 diferent locations.
One is a web server and the other a crm system.
People update and register on web, when they do changes i need to insert or update the changes to my crm server.
I have a view on web server where i can select from but i need to
insert into on duplicate update only fields that changed and then in a description
show
wich fields were updated?
I have no clue how to start.
You can not determine the differences on fields after changing them.
You can however select and store the contents prior to the update and then compare it with the new contents.
The question then becomes: Do you need the differences per column?
If yes: Pre-select and do the difference yourself (in the
application).
If no: Use the method described by #Ogelami (and accept his answer :)
On a side note: The Pre-Select thing won't work as well, when you start using several mysql servers, since you might run into issues with drifting data (ie one server is behind in inserted data). When this occurs, the method will get a bit more complex.
Perhaps something like this?
INSERT INTO table ON DUPLICATE UPDATE table SET field = value WHERE field != 'value'
and you might want to look into this to see if there are Affected rows.
Alright, I've got a question, not really an issue.
I've got a table in my database, fairly small, only 3 columns but potential to grow. I've got two solutions to my problem, but not sure why to use one or the other.
I've got a piece of data, which might or might not already be in the database. Two ways to solve this. I've got the unique ID, so it is easy to check.
Check if the records exists in the database, and if not, INSERT INTO database
Use REPLACE INTO, because I've got the ID already.
My question now is. Which one is better to use. What are the pros and cons in using either of the 2 results. Or is there a better result?
A note, the data is exactly the same, so there is no chance the record gets updated with a newer value. Thus the REPLACE INTO will insert data which is already there.
REPLACE INTO is not recommended here - you don't really need to replace anything. It does DELETE followed by INSERT, with all the consequences. For example all indexes have to be updated, which leads to unnecessary work and index fragmenting if you use it frequently.
On the other hand there is ON DUPLICATE KEY UPDATE, which is used mainly for counters, but you are not updating your row with increments or any other value changes, so you would have to use weird syntax like SET id=id or something similar.
Checking if the record exists in the database would be the best solution for you, but instead of using another query let mysql do that check for you and use:
`INSERT IGNORE INTO ...`
This way if you try to insert any row with duplicated unique or primary key it simply won't be inserted without generating any error. Note the side effect of possibly missing other error messages, but if you know exactly what you insert you should be fine.
I am having an issue with an update command. It's not as if the code is written wrong; I've had three people look at it and not come up with a solid answer of why the code is not working. So in lieu of getting the code to work, is it possible to use INSERT to replace the data in the database instead of using UPDATE?
No. Insert will only create a new row.
Well … you could perform a delete followed by an insert, but that way lies madness.
For MySQL, there's REPLACE that deletes possible existing row and inserts (mysql doc) or, equivalaent syntax INSERT ... ON DUPLICATE KEY UPDATE (mysql doc).
For some other databases, there's MERGE - Oracle, MS SQL
Anyway, these are good to know of, but you'd rather fix the UPDATE in the first place.
You would have to insert a new row, check that has inserted row worked and then delete the original, this will cause you all sorts of problem with unique keys.
Post your code and the error you're getting someone here might be able to spot something that has been missed.
I am inserting a value in to the table using php-mysql its getting inserted correctly.The insertion file in php is called through the ajax request. My problem is in some of the firefox version the request is triggered twice at some times and the records are inserted 6times with same datas in the table..How to prevent such situation without using unique concept...
It sounds like the SQL does what it is told to. It's up to you to not execute the query with the same data over and over.
As you stated "in some of the firefox version the request is triggered twice", the problem is most likely in your client code, post that code for us to be able to help you.
(This should have been a comment but I'm too low on rep pts.)
MySQL offers a REPLACE command which is similar to INSERT but silently ignores duplicates. Documentation here.
Using jQuery might help you (if you're not already). You can ensure that your code isn't executed too early with jquery's built in $(document).ready() event.
Also look at what is triggering the ajax call, if it is being done more times than you expected. You could also do some server-side checking to make sure that a query was not already submitted.
Because you don't want to go with a UNIQUE index...
...I realized similiar problems by simply querying the table before the insert to look if the record already exists. I also implemented a time limit for the look up.
So this is what I do:
I check the data if it's valid for insert in the table.
I use this exact data for a select on the table, limited to all entries in the last 5 minutes.
If the select returns no result, I insert the data in the table, otherwise I ignore it as "dublicate entry".