MySQL - Field 'id' doesn't have a default value - php

I can't insert any rows into my database, and the error I'm getting is:
This doesn't make any sense as it was working fine before, nothing has changed as far as I know. The ID field is set to primary, not null and auto increment:
I was able to insert a row manually through PHPMyAdmin. Heres the code I'm inserting with:
$query = "INSERT INTO wp_genomics_results (file_id,snp_id,genotype,reputation,zygosity) VALUES (?,?,?,?,?)";
$stmt = $ngdb->prepare($query);
$file_id = $this->fileID;
$snp_id = $row['id'];
$genotype = $this->formatGenotype($extractedGenotype);
$zygosity = $this->assignZygosity($genotype,$minor_allele);
$reputation = $this->assignReputation($zygosity,$genotypes);
$stmt->bind_param("sssss", $file_id,$snp_id,$genotype,$reputation,$zygosity);
$stmt->execute();
I tried deleting the table and creating a new table but it didn't fix it. Is there anything else I can do to try and diagnose and fix this?

make sure for this line:
$stmt->bind_param("sssss",
$file_id,$snp_id,$genotype,$reputation,$zygosity);
First parameter of bind_param() you used is "sssss" that means all off data is string. Please fix it as the right type data of your type on table database.
Please use "i" for integer. For example:
$stmt->bind_param("iisss",
$file_id,$snp_id,$genotype,$reputation,$zygosity);
I make the code above as an example because I can not see all of your table descibe.

I tried inserting with the WordPress database connection:
$wpdb->query("INSERT INTO wp_genomics_results (file_id,snp_id,genotype,reputation,zygosity) VALUES ('$file_id','$snp_id','$genotype','$reputation','$zygosity')");
and it works, but if I try using an identical query with my own database connection:
$db = new mysqli('localhost', NG_DB_USER, NG_DB_PASS, NG_DB_NAME);
$db->query("INSERT INTO wp_genomics_results (file_id,snp_id,genotype,reputation,zygosity) VALUES ('111','$snp_id','$genotype','$reputation','$zygosity')");
I get the same error:
Error No: 1364 - MySQL error Field 'id' doesn't have a default value
I don't understand why it works with wordpress but not my own database connection. I went into my mysql.ini file and changed this:
sql-mode="STRICT_ALL_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ZERO_DATE,
NO_ZERO_IN_DATE,NO_AUTO_CREATE_USER"
to this:
sql-mode=""
and now I can insert a row, the error stopped happening. I still don't understand why this error was occuring to begin with. And now theres a new error happening:
Duplicate entry '0' for key 'PRIMARY'
I don't understand it because the id column is set to auto increment. Theres also no rows in there with ID = 0. I even emptied the table to make absolute sure there is no row in there with ID = 0. I'm very confused about whats happening. Heres the output of the table structure:
> mysql> SHOW CREATE TABLE wp_genomics_results;
| wp_genomics_results | CREATE TABLE `wp_genomics_results` (
`id` bigint(11) NOT NULL AUTO_INCREMENT,
`file_id` int(11) NOT NULL,
`snp_id` int(11) NOT NULL,
`genotype` varchar(3) NOT NULL,
`reputation` varchar(3) NOT NULL,
`zygosity` int(3) NOT NULL,
PRIMARY KEY (`id`),
KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)
I notice it says 1 row in set, but the table is actually empty. And once again, I'm able to insert a new row through PHPMyAdmin:

Oh God I feel like an idiot. All this time, the problem was that I had the wrong database selected. So it was querying a table from a different database, and this tables ID field didn't have auto increment set. Ah well, it was a good learning experience, getting to know MySQL better.

EDIT
The table definition looks really strange. It looks like there's a second index on the id column. The id column is already defined as the PRIMARY KEY.
It's this line in the table definition that is bothers me...
KEY `id` (`id`)
It's bizarre that MySQL would even let you add a second index on the same column, and not return an error like "such an index already exist" or "the set of columns is already indexed" or such.
I recommend you run a statement to drop the index named id. Execute either
DROP INDEX `id` ON `wp_genomics_results`;
-or-
ALTER TABLE `wp_genomics_results` DROP KEY `id`;
It's possible that this index was contributing to the issue.
ORIGINAL ANSWER
I suggest you figure out exactly which statement is throwing an error.
I suspect it's not the execution of INSERT INTO wp_genomics_results statement.
If it were me, I'd take a look at the assignZygosity and assignReputation functions. I suspect the culprit is in down in there.
I suspect there's something going on in those functions. My guess (just a guess) is that one of those functions is performing a lookup to get a value for a foreign key. And, if a foreign key value isn't found, something is being executed to INSERT a row into the referenced table. There must be some reason that function is being called, some reason we're not just using the value supplied as a parameter...
The formatGenotype function is also a suspect, by proximity. (I'm less a-feared of that function name... but again, I have no idea what that function is doing.)
If that's not the issue, if it's really the execution of the INSERT statement shown in the code, then I'd look for a "BEFORE INSERT" trigger on the wp_genomics_results table... maybe the trigger is performing an insert to some other table.
As a quick test, I'd comment out the calls to those functions, and just assign a literal values to $zygosity and $reputation.
I want to know the exact line number in the exact file where the error is being thrown.
I also want the complete error message from MySQL.
Following every execution of a database interaction, I want to check the return, and if there's an error, I want (for debugging purposes) a unique message that indicates where we are in the code when the error is thrown, along with the complete error message returned from MySQL (mysqli_error).
I'm not going to just assume, without evidence, that it's the execution of this particular statement that's causing the error.
And if it really is this statement, then we'd need to take a look at the actual MySQL definition of the table... the output from a SHOW CREATE TABLE wp_genomics_results statement.
And we want to make sure that we are looking at the same MySQL instance and database that the code is connecting to, and not some other MySQL instance or database.

Related

#1062 - Duplicate entry '81057' for key 'PRIMARY'

I am not fluent in using phpmyadmin so please be gentle.
I have transferred wordpress sites in the past but they have small databases. Ive now moved a new clients site to my hosting and it is running with this error:
INSERT INTO `wp_options` VALUES ( 81057,
'_wc_session_6f1ee0a5a9d89e47f7941c9e3b3e1fed',
'a:20:{s:4:"cart";s:309:"a:1:{s:32:"7b1ce3d73b70f1a7246e7b76a35fb552";a:9:{s:10:"product_id";i:2103;s:12:"variation_id";s:0:"";s:9:"variation";s:0:"";s:8:"quantity";i:1;s:10:"line_total";d:23;s:8:"line_tax";i:0;s:13:"line_subtotal";d:23;s:17:"line_subtotal_tax";i:0;s:13:"line_tax_data";a:2:{s:5:"total";a:0:{}s:8:"subtotal";a:0:{}}}}";s:15:"applied_coupons";s:6:"a:0:{}";s:23:"coupon_discount_amounts";s:6:"a:0:{}";s:19:"cart_contents_total";d:23;s:20:"cart_contents_weight";i:0;s:19:"cart_contents_count";i:1;s:17:"cart_contents_tax";i:0;s:5:"total";i:0;s:8:"subtotal";d:23;s:15:"subtotal_ex_tax";d:23;s:9:"tax_total";i:0;s:5:"taxes";s:6:"a:0:{}";s:14:"shipping_taxes";s:6:"a:0:{}";s:13:"discount_cart";i:0;s:14:"discount_total";i:0;s:14:"shipping_total";i:0;s:18:"shipping_tax_total";i:0;s:9:"fee_total";i:0;s:4:"fees";s:6:"a:0:{}";s:10:"wc_notices";N;}',
no' ) ;`
#1062 - Duplicate entry '81057' for key 'PRIMARY'
I genuinely do not have a clue what this means and how to change it. I get that there is a duplicate entry and its to do with the primary key - which is set on option_id.
What i don't get is why it doesn't just add the entries into the database and auto increment them - which it is set to do? Also how can i resolve the issue and add the database?
please help !
AUTO_INCREMENT is a default value. If you specify a value for the field it will be used instead.
You can omit the value in the insert statement or use NULL instead.
It looks like the table in your source database has some inconsistency since you are only trying to copy all records to your new database.
Check if there are multiple records with same option_id in your source table and if there are some try to resolve them and then try the import again.
As i understand you are trying to do the manual transfer of the whole database and in that case AUTO_INCREMENT just wont work since you will break the relations between your model entities.
The way I see it, you have two options.
Omit the primary key value and allow mysql to create a new row and auto increment it. Of course this will require you to specify the columns.
INSERT INTO `wp_options`(column2, column3, etc)
VALUES('_wc_session_6f1ee0a5a9d89e47f7941c9e3b3e1fed', ...);
Notice that I left out the primary key
If the data needs to be added to that specific row, do an UPDATE instead.
UPDATE wp_options SET column2='_wc_session_6f1ee0a5a9d89e47f7941c9e3b3e1fed',
column3='something else', ...
WHERE column1=81057

Confused about SQL syntax to be used in phpMyAdmin dialect

I am using SQL statements embedded in two PHP files to produce a database that appears in HTML as well as in phpMyAdmin. I have created a table like with the following command:
$sql = "CREATE TABLE WeatherCenter (OutgoingLongwaveRadiation VARCHAR(30))";
In the second PHP file, I have:
$sql = "ALTER TABLE WeatherCenter
ADD COLUMN (
`Barometric Pressure` SMALLINT NOT NULL,
`CloudType` VARCHAR(70) NOT NULL,
`WhenLikelyToRain` VARCHAR(30) NOT NULL);";
When I execute the files, I keep getting "Undefined column Barometric Pressure does not exist in filed list". I realized that this is because somewhere else in my PHP file I listed the variable as BarometricPressure and not Barometric Pressure (ie. one has a gap, and the other doesn't). When I corrected the mistake in the ALTER TABLE by deleting the gap, the same error message STILL appeared in the phpMyAdmin database. It seems to me that changing the name of the field in the PHP file does NOT change it in the phpMyAdmin database. As a result, no data is being transmitted to the database.
Could someone tell me if I changed the syntax of the above to
$sql = "ALTER TABLE WeatherCenter
ADD COLUMN `Barometric Pressure` SMALLINT NOT NULL AFTER `OutgoingLongwaveRaadiation`,
ADD COLUMN `CloudType` VARCHAR(70) NOT NULL AFTER `BarometricPressure`,
ADD COLUMN `WhenLikelyToRain` VARCHAR(30) NOT NULL AFTER `CloudType` ;";
will the problem go away? I mean, do you HAVE to use an "ADD COLUMN" before EACH field name, and do you HAVE to specify the "AFTER previous field name"? Do you have to take these additional measures to ensure that any mistake in the field name that appears in the phpMyAdmin can be erased by rewriting your code in the PHP file? Could someone simply tell me what the correct syntax is please, because there appears to be inconsistencies. Some of the ALTER TABLE statements do not have opening and close brackets and no backticks, but other ALTER TABLE statements make it clear that you must have opening and closing brackets and backticks such that the last few characters in the ALTER TABLE statement MUST be );";
I am throughly confused.

Mysterious INSERT UPDATE error

I have a table that looks like (irrelevant columns subtracted):
PRIMARY KEY(AUTO-INCREMENT,INT),
CLIENTID(INT),
CLIENTENTRYID(INT),
COUNT1(INT),
COUNT2(INT)
Now, the CLIENTID and CLIENTENTRYID is a unique combined index serving as a duplication prevention.
I use PHP post input to the server. My query looks like:
$stmt = $sql->prepare('INSERT INTO table (COUNT1,COUNT2,CLIENTID,CLIENTENTRYID) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE COUNT1=VALUES(COUNT1),COUNT2=VALUES(COUNT2)');
$stmt->bind_param("iiii",$value,$value,$clientid,$cliententryid);
The SQL object has auto commit enabled. The "value" variable is reused as the value in COUNT1 and COUNT2 should ALWAYS be the same.
Okay - that works fine, most of the time, but randomly, and I cannot figure out why, it will post 0 in COUNT2 - for an entirely different row.
Any ideas how that might occur? I can't see a pattern (it doesn't happen after a failed attempt, which is why the unique index exists, so that a new attempt will not cause duplicates). It seems to be completely random.
Is there something I've misunderstood about ON DUPLICATE KEY UPDATE? The VERY weird thing is that it updates A DIFFERENT row incorrectly - not the one you insert.
I realize other factors might affect this, but now I'm trying to rule out my SQL logic as a source of error.
Aside from the PRIMARY KEY on the auto_increment column, there is only ONE UNIQUE key defined the table, and that's defined on (CLIENTID,CLIENTENTRYID), right?
And there are no triggers defined on the table, right?
And you are (obviously) using a prepared statement with bind placeholders.
It doesn't really matter if those two columns (CLIENTID and CLIENTENTRYID) are defined as NOT NULL or not; MySQL will allow multiple rows with NULL values; that doesn't violated the "uniqueness" enforced by a UNIQUE constraint. (This the same as how Oracle treats "uniqueness" of NULL values, but it is different from how SQL Server enforces it.)
I just don't see any way that the statement you show, that is:
INSERT INTO `mytable` (COUNT1,COUNT2,CLIENTID,CLIENTENTRYID) VALUES (?,?,?,?)
ON DUPLICATE KEY
UPDATE COUNT1 = VALUES(COUNT1)
, COUNT2 = VALUES(COUNT2)
... theres no way that Would cause some other row in the table to be updated.
Either the insert action succeeds, or it throws a "duplicate key" exception. If the "duplicate key" exception is thrown, the statement catches that, and performs the UPDATE action.
Given that (CLIENTID,CLIENTENTRYID) is the only unique key on the table (apart from the auto_increment column, not referenced by this statement), the update action will be equivalent to this statement:
UPDATE `mytable`
SET COUNT1 = ?
, COUNT2 = ?
WHERE CLIENTID = ?
AND CLIENTENTRYID = ?
... using the values supplied in the VALUES clause of the INSERT statement.
Bottom line, there isn't an issue in anything OP showed us. The logic is sound. There is something else going on, apart from this SQL statement.
OP code shows as using scalars (and not array elements) as arguments in the bind_param call, so that whole messiness of passing by reference shouldn't be an issue.
There's not an issue with the SQL statement OP has shown, based on everything OP told us and shown us. The issue reported has to be something other than the SQL statement.
Looking at the MySQL doc, it says that given an insert statement
INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;
if column a and b are unique, the insert is equivalent to an update statement with a WHERE clause containing an OR instead of an AND:
UPDATE table SET c=c+1 WHERE a=1 OR b=2 LIMIT 1;
And to quote from the documentation,
If a=1 OR b=2 matches several rows, only one row is updated. In
general, you should try to avoid using an ON DUPLICATE KEY UPDATE
clause on tables with multiple unique indexes.
Hope this helps.
UPDATE:
As per further discussion, OP will consider re-visiting existing database design. OP also has another table with similar multiple unique index spec, but without the same problem by utilizing INSERT IGNORE.
I found the answer.
As everyone here correctly suggested, this was something else. For some completely bizarre reason, the button I used to open the "add new entry" somehow POST'ed to set arrived = 0 on a selected object in a table view that has nothing to do with the button.
This must have been a UI linking somewhere in my Storyboard.
I'm sorry I wasted so much of your time guys. At least I learned a little more about SQL and indexes.
i think problem is with your are using values in UPDATE COUNT1=VALUES(COUNT1),COUNT2=VALUES(COUNT2) try to use like this
ON DUPLICATE KEY UPDATE COUNT1 = $v1,COUNT2 = $v2;

Why does a mysql Insert query fail *only* when the table is empty?

I am running these two statements one right after another in some PHP code.
INSERT INTO input (ID) VALUES('1');
UPDATE input SET `vendor_name` = 'some name' WHERE ID=1
If the database table is empty (meaning I just truncated the table), no data is created, no warnings appear. It's as if I never executed the query.
If I then run just
INSERT INTO input (ID) VALUES('1');
On this exact same clear table, an entry is created no problem.
After that, if I again run the same INSERT/UPDATE querys
INSERT INTO input (ID) VALUES('2');
UPDATE input SET `vendor_name` = 'some name' WHERE ID=2
Then the data is created and the vendor_name set appropriately. What is going on here?? I seem to be misunderstanding something fundamental about inserting data into a database. Can I not execute statements back-to-back like this on an empty table?
To pre-empt the inevitable silly questions like 'does the column exist?', here is some extra notes:
NO warnings ever appear. This really bugs me. The INSERT/UPDATE seems to fail silently. (yes, yes, I have set error reporting on and I checked the logs)
The appropriate columns/tables/databases/permissions exist and are defined (remember the query works fine if there is an empty row in the table)
ID is the primary key. The numbers I used for IDs (1,2, whatever) do not seem to matter. I could just as well reverse them, or use 101 and 102, whatever.
Create table looks like so: CREATE TABLE IF NOT EXISTS $tablename (ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY). Columns are added dynamically by users. So right now there's about 100 columns in the table ( keep in mind this shouldn't matter. I'm only trying to update one column, and that update works fine if there is data in the table)
Sneaking a Count(*) query in there reveals that the row is created, but then disappears after the Update statement. (Perhaps the row wasn't completed, or something, and there's a 'make sure the insert is finished' query I need to run?)
Try this code.... for me its works....
INSERT INTO `input` (ID) VALUES('1');
UPDATE `input` SET `vendor_name` = 'some name' WHERE ID=1

Auto increment stopped in MySQL?

I'm working on a script that sadly I inherited - with no commenting or anything. Argh!
For testing purposes I duplicated one of the tables in the database which had an auto-incrementing ID. When the data is saved to the database, though, the ID number just reads "0" -- which is the default for that column. I'm not sure why it's not auto increasing anymore... any thoughts? Thank you!
Are you sure you set the field in the duplicate table to auto-increment? Try running:
ALTER TABLE `duplicate_table` CHANGE `ai_key` `ai_key` INT( key_length ) NOT NULL AUTO_INCREMENT
And see if it is set or not.
Did you create the new table from scratch or as a real copy? If the column is supposed to auto increment it should be a primary (or at least a unique) key, with no default value.
Just to double check use the sql statement to show the show create table syntax for both tables and compare.
show create table <table>
It sounds like your column isn't actually auto_increment any more. This has happened to me a couple of times because there was a bug (?) in phpMyAdmin which I used to create backups: it wouldn't add the auto_increment keyword into the CREATE TABLE statements. That was a massive pain in the butt...

Categories