comparing a varchar field to the number zero returns as if its a true match - mysql

i am looking for some work around on this problem and/or i need it to reply with an empty result or the boolean false.
using the sql statement on MySQL
`SELECT * FROM users WHERE verify = 0 LIMIT 1`
the code above returns the second row in the table.
Here is the table i used:
CREATE TABLE IF NOT EXISTS `users` (
`user_id` bigint(20) unsigned NOT NULL,
`username` varchar(30) NOT NULL,
`password` varchar(60) NOT NULL,
`email` varchar(30) NOT NULL,
`firstname` varchar(30) DEFAULT NULL,
`lastname` varchar(30) DEFAULT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1',
`verify` varchar(32) NOT NULL,
`verified` bit(1) NOT NULL DEFAULT b'0'
) ENGINE=InnoDB AUTO_INCREMENT=37 DEFAULT CHARSET=latin1;
INSERT INTO `users` VALUES(1, 'admin', '$2y$10$id6rHN6Zy8XHmCkWlAMvGO8pr3K4OD1zfFAZMaVgoGXbezY8SXcT2', 'admin#admin.com', 'Firstname', 'Lastname', 1, '21232f297a57a5a743894a0e4a801fc3', b'1');
INSERT INTO `users` VALUES(36, 'client', '$2y$10$gdtPImQhYoCIiTpTs/veW.BXsWUz6Zcxb.TY6XXQNO6uf5Q7kx99.', 'client#client.com', 'client', 'client', 1, 'cf3873cdefaefa2cc2c4f1efbba23202', b'0');
--edit, sorry did not specify want i wanted
i don't want it to return anything or maybe how do i make it that it would return false or empty result.
right now, i am using a nasty workaround by modifying the zero result and making it a text "zero" before passing it to the sql query. works but, if there is something better way that you can suggest it would be much appreciated.

I'm not sure what you expect to happen. When you write:
where verify = 0
MySQL has a conundrum. verify is a character string and 0 is an integer. They are not comparable, so MySQL converts one to the other. In this case, it will convert verify to an integer value, getting 0, and they match.
If you want a string comparison, then use:
where verify = '0'
However, that returns the same result.
If you want it to compare to the character value of 0, then perhaps you want:
where verify = '\0'

Related

MariaDb vs MySQL JSON_ARRAYAGG JSON_OBJECT Without Escaping

I have a select query, which works just fine in my localhost MySQL database environment. It should return json object.
When I run the same query on my hosted public server with MariaDB 10.5.15 installed, the returned json includes several backslashes, escaping characters.
Here is the code:
SELECT
json_object(
'id', C1.Category1ID,
'text', C1.Category1Name,
'nodes', JSON_ARRAYAGG(
JSON_OBJECT(
'id', C2.Category2ID,
'text', C2.Category2Name,
'nodes', C2.nodes,
'class', 'nav-level-2',
'href', 'admin-categories-2.php'
)
),
'class', 'nav-level-1',
'href', 'admin-categories-1.php'
) AS JSON
FROM categories_1 C1
LEFT JOIN (
SELECT
C2.Category1ID,
C2.Category2ID,
C2.Category2Name,
JSON_ARRAYAGG(
JSON_OBJECT(
'id', C3.Category3ID,
'text', C3.Category3Name,
'class', 'nav-level-3',
'href', 'admin-categories-3.php'
)
) as nodes
FROM categories_2 C2
LEFT JOIN categories_3 C3 ON C3.Category2ID = C2.Category2ID AND C3.Category3Status = 1
WHERE C2.Category2Status = 1
GROUP BY C2.Category2ID
ORDER BY C2.Category2Order, C3.Category3Order
) C2 ON C2.Category1ID = C1.Category1ID
WHERE C1.Category1Status = 1
GROUP BY C1.Category1ID
ORDER BY C1.Category1Order
;
My question is how to write this query correctly for MariaDB.
I am attaching result from MySQL (img1) and MariaDB (img2).
I am attaching create and insert statements for db here:
CREATE TABLE `categories_1` (
`Category1ID` int(11) NOT NULL AUTO_INCREMENT,
`Category1Name` varchar(45) DEFAULT NULL,
`Category1Name_FR` varchar(45) DEFAULT NULL,
`Category1Photo` varchar(45) DEFAULT NULL,
`Category1Order` int(3) DEFAULT NULL,
`Category1Status` int(1) DEFAULT 1,
PRIMARY KEY (`Category1ID`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='Top level category'
CREATE TABLE `categories_2` (
`Category2ID` int(11) NOT NULL AUTO_INCREMENT,
`Category2Name` varchar(45) DEFAULT NULL,
`Category2Name_FR` varchar(45) DEFAULT NULL,
`Category2Order` int(3) DEFAULT NULL,
`Category2Status` int(1) DEFAULT 1,
`Category1ID` int(11) DEFAULT NULL COMMENT 'To which parent level category it fits',
PRIMARY KEY (`Category2ID`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COMMENT='Mid level category'
CREATE TABLE `categories_3` (
`Category3ID` int(11) NOT NULL AUTO_INCREMENT,
`Category3Name` varchar(45) DEFAULT NULL,
`Category3Name_FR` varchar(45) DEFAULT NULL,
`Category3Order` int(3) DEFAULT NULL,
`Category3Status` int(1) DEFAULT 1,
`Category2ID` int(11) DEFAULT NULL COMMENT 'To which parent level category it fits',
PRIMARY KEY (`Category3ID`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COMMENT='Bottom level category'
INSERT INTO `categories_1` VALUES (1,'Meat','Meat-fr','meat.jpg',1,1),(2,'Fish & Sea Food',NULL,'fish.jpg',2,1),(3,'Fruit & Vegetables',NULL,'fruit-veg.jpg',3,1),(4,'Test L1',NULL,'categories-default.jpg',4,0);
INSERT INTO `categories_2` VALUES (1,'Beef','Feef-fr',1,1,1),(2,'Lamb',NULL,2,1,1),(3,'Pork',NULL,3,1,1),(4,'Veal',NULL,4,1,1),(5,'Poultry-Fowl',NULL,6,1,1),(6,'Sausages and Bacon',NULL,5,1,1),(7,'Salmon',NULL,8,1,2),(8,'Flat Fish',NULL,9,1,2),(9,'Common Fish',NULL,10,1,2),(10,'Squid family',NULL,11,1,2),(11,'Shellfish',NULL,12,1,2),(12,'Tuna',NULL,13,1,2),(13,'Other Fish',NULL,14,1,2),(14,'TEST L2',NULL,7,0,1);
INSERT INTO `categories_3` VALUES (1,'Specialist Beef','Specialist Beef-fr',1,1,1),(2,'Wagyu',NULL,2,1,1),(3,'Japanese Wagyu',NULL,3,1,1),(4,'Other Beef',NULL,4,1,1),(5,'All Lamb',NULL,6,1,2),(6,'All Pork',NULL,5,1,3),(7,'All Veal',NULL,7,1,4),(8,'All Poultry-Fowl',NULL,11,1,5),(9,'Pork Sausages',NULL,8,1,6),(10,'Other meats',NULL,9,1,6),(11,'Bacon',NULL,10,1,6),(12,'All Salmon',NULL,12,1,7),(13,'All Flat Fish',NULL,13,1,8),(14,'All Common Fish',NULL,14,1,9),(15,'All Squid family',NULL,15,1,10),(16,'All Shellfish',NULL,16,1,11),(17,'All Tuna',NULL,17,1,12),(18,'All Other Fish',NULL,18,1,13),(19,'TEST L3',NULL,999,0,14);
MariaDB have no JSON datatype (JSON keyword is an alias for LONGTEXT keyword only), it may treate string type value as JSON only.
You use construction JSON_ARRAYAGG( JSON_OBJECT( .... In MariaDB the value produced by JSON_OBJECT is string ! It is one solid string, not complex value of JSON datatype. Hence during JSON_ARRAYAGG this solid string value which contains the chars needed in quoting is processed, and all doublequote chars are quoted.
See FIDDLE, especially last and pre-last code blocks. In pre-last block pay special attention to the doubequote chars which wraps the whole value (not inner doublequotes which are quoted by the slashes).
I do not see the way to fix this in MariaDB. There is no method to tell the function that the value provided as an argument is not string but JSON - there is no such datatype.
Wait until MariaDB implements JSON datatype (if) and upgrade.

MySQL null value not inserting

I have a query like
INSERT INTO support_users VALUES("1",,"2","1","4",,,"2017-05-06 20:24:36");
but new MySQL not inserting given error Error Code: 1064
but I changed it to
INSERT INTO support_users VALUES("1","","2","1","4",,,"2017-05-06 20:24:36");
working
but previous MySQL not having such an issue.how to solve that. without changing query
table definition
CREATE TABLE support_users (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`client` int(11) DEFAULT NULL,
`user` int(11) DEFAULT NULL,
`ticket` int(11) DEFAULT NULL,
`scope` int(11) DEFAULT NULL,
`notify` tinyint(1) DEFAULT NULL,
`email` tinyint(1) DEFAULT NULL,
`added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=46 DEFAULT CHARSET=utf8;
Firstly, respect the Datatype. If its Integer don't use quotes.
The right way to approach your problem will be use of NULL. So this works across any version of MySQL.
INSERT INTO support_users VALUES(1,NULL,2,1,4,NULL,NULL,'2017-05-06 20:24:36');
1)
Integer column values should not be quoted.
So "1" becomes 1
2)
Auto Increment values should not be manally given to the SQL -- let it work it out itself.
3)
Inserting NULL using the NULL keyword.
4)
Your date-time column is set in its definition to show the current date-time of the row being inserted when it is inserted. As you are inserting (rather than updating, etc.) you therefore do not need to include this data.
5)
It is easier for your sanity to also list which columns are being added to with the INSERT instruction.
6)
Use single quotes ' around string data not double quotes ("), when working directly with MySQL.
Result:
INSERT INTO support_users( `id`, `ticket`, `scope` , `notify`)
VALUES (1, 2,1,4);
This will cause errors if you try to insert twice, because you are forcing the Primary Key (id) to be 1. To avoid this, skip the Auto Increment (id) column value.
Or for clarity only; the full SQL:
INSERT INTO support_users VALUES (1, NULL, 2, 1, 4, NULL, NULL, '2017-05-06 20:24:36');
Skipping the Auto Increment (id) column value (as referenced above):
INSERT INTO support_users VALUES (NULL, NULL, 2, 1, 4, NULL, NULL, '2017-05-06 20:24:36');

create event of mysql with some logic not working

I am trying to create an event in mysql
Schema :
create event alert_2 ON SCHEDULE EVERY 300 SECOND DO
BEGIN
DECLARE current_time DATETIME;
DECLARE attempted INT;
DECLARE completed INT;
DECLARE calc_value DECIMAL;
set #current_time = CONVERT_TZ(NOW(), ##session.time_zone, '+0:00');
select count(uniqueid) as #attempted,SUM(CASE WHEN seconds > 0 THEN 1 ELSE 0 END) as #completed from callinfo where date >= DATE_SUB(#current_time, INTERVAL 300 SECOND) AND date <= #current_time;
SET #calc_value = (ROUND((#completed/#attempted)*100,2);
IF #calc_value <= 10.00 THEN
INSERT INTO report(value1) value (#calc_value);
END IF;
END;
Problem :
Event is not going to creating
Need suggestion :
Is this create any overload on callinfo table ?
If yes,Would you like to suggest any other way to achieve same thing ?
May i create similar but multiple around 50.Will it create huge load on call info table.
Call info schema :
CREATE TABLE `callinfo` (
`uniqueid` varchar(60) NOT NULL DEFAULT '',
`accountid` int(11) DEFAULT '0',
`type` tinyint(1) NOT NULL DEFAULT '0',
`callerid` varchar(120) NOT NULL,
`callednum` varchar(30) NOT NULL DEFAULT '',
`seconds` smallint(6) NOT NULL DEFAULT '0',
`trunk_id` smallint(6) NOT NULL DEFAULT '0',
`trunkip` varchar(15) NOT NULL DEFAULT '',
`callerip` varchar(15) NOT NULL DEFAULT '',
`disposition` varchar(45) NOT NULL DEFAULT '',
`date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`debit` decimal(20,6) NOT NULL DEFAULT '0.000000',
`cost` decimal(20,6) NOT NULL DEFAULT '0.000000',
`provider_id` int(11) NOT NULL DEFAULT '0',
`pricelist_id` smallint(6) NOT NULL DEFAULT '0',
`package_id` int(11) NOT NULL DEFAULT '0',
`pattern` varchar(20) NOT NULL,
`notes` varchar(80) NOT NULL,
`invoiceid` int(11) NOT NULL DEFAULT '0',
`rate_cost` decimal(20,6) NOT NULL DEFAULT '0.000000',
`reseller_id` int(11) NOT NULL DEFAULT '0',
`reseller_code` varchar(20) NOT NULL,
`reseller_code_destination` varchar(80) DEFAULT NULL,
`reseller_cost` decimal(20,6) NOT NULL DEFAULT '0.000000',
`provider_code` varchar(20) NOT NULL,
`provider_code_destination` varchar(80) NOT NULL,
`provider_cost` decimal(20,6) NOT NULL DEFAULT '0.000000',
`provider_call_cost` decimal(20,6) NOT NULL,
`call_direction` enum('outbound','inbound') NOT NULL,
`calltype` enum('STANDARD','DID','FREE','CALLINGCARD') NOT NULL DEFAULT 'STANDARD',
`profile_start_stamp` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`answer_stamp` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`bridge_stamp` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`progress_stamp` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`progress_media_stamp` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`end_stamp` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`billmsec` int(11) NOT NULL DEFAULT '0',
`answermsec` int(11) NOT NULL DEFAULT '0',
`waitmsec` int(11) NOT NULL DEFAULT '0',
`progress_mediamsec` int(11) NOT NULL DEFAULT '0',
`flow_billmsec` int(11) NOT NULL DEFAULT '0',
`is_recording` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0 for On,1 for Off'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='callinfo';
ALTER TABLE `callinfo` ADD UNIQUE KEY `uniqueid` (`uniqueid`), ADD KEY `user_id` (`accountid`);
More Information about callinfo table :
In call info table around 20K/hour rercords are inserted.
Please suggest ,If need to apply any indexing in schema to get good performance.
Some suggestions:
user-defined variables (variables named starting with # character) are separate and distinct from local variables
there's no need to declare local variables that aren't referenced
use local variables in favor of user-defined variables
a column alias (identifier) that starts with # character need to be escaped (or MySQL will throw a syntax error)
assigning a column alias (identifier) that looks like a user-defined variable is just a column alias; it is not a reference to a user-defined variable
use SELECT ... INTO to assign scalar values returned from statement into local variables and/or user-defined variables
declaring datatype DECIMAL is equivalent to specifying DECIMAL(10,0)
in INSERT ... VALUES statement the keyword is VALUES not VALUE
best practice is to give local variables names that are different from column names
best practice is to qualify all column references
its a bit odd to insert only a single column, a calculated value, into a table without some other identifying values (it's not illegal. it may be exactly what the specification calls for. it just strikes me as a bit odd. I bring it up in light of the code as written, because appears that the author of the code is not familiar with MySQL.)
using CONVERT_TZ is a bit odd; given that any datetime value referenced in a SQL statement will be interpreted in the current session time zone; we're kind of assuming that the date column is DATETIME datatype, but that's just a guess.
to create a MySQL stored program that contains semicolons, the DELIMITER for the session needs to be changed to character(s) that don't appear in the stored program definition
Rather than address each individual problem in the stored program, I'm going to suggest a revision that does what it looks like the original code was intended to do:
DELIMITER $$
CREATE EVENT alert_2 ON SCHEDULE EVERY 300 SECOND DO
BEGIN
DECLARE ld_current_time DATETIME;
DECLARE ln_calc_value DECIMAL(20,2);
-- DECLARE li_attempted INT;
-- DECLARE li_completed INT;
SET ld_current_time = CONVERT_TZ(NOW(), ##session.time_zone, '+0:00');
SELECT ROUND( 100.0
* SUM(CASE WHEN c.seconds > 0 THEN 1 ELSE 0 END)
/ COUNT(c.uniqueid)
,2) AS calc_value
-- , COUNT(c.uniqueid) AS attempted
-- , SUM(CASE WHEN c.seconds > 0 THEN 1 ELSE 0 END) AS completed
FROM callinfo c
WHERE c.date > ld_current_time + INTERVAL -300 SECOND
AND c.date <= ld_current_time
INTO ln_calc_value
-- , li_attempted
-- , li_completed
;
IF ln_calc_value <= 10.00 THEN
INSERT INTO report ( value1 ) VALUES ( ln_calc_value );
END IF;
END$$
DELIMITER ;
For performance, we want to have an index with date as the leading column
... ON `callinfo` (`date`, ...)
Ideally (for the query in this stored program) the index with the leading column of date would be a covering index (including all of the columns that are referenced in the query), e.g.
... ON `callinfo` (`date`,`seconds`,`uniqueid`)
Q: Is this create any overload on callinfo table ?
Since this runs a query against callinfo table, it will need to obtain shared locks. With an appropriate index available, and assuming that 5 minutes of call info is a smallish set of rows, I wouldn't expect this query to contribute significantly towards performance problems or contention issues. If it does cause a problem, I would expect that this query in this stored program isn't the root cause of the problem, it will only exacerbate a problem that already exists.
Q: If yes,Would you like to suggest any other way to achieve same thing ?
It's difficult to suggest alternatives to achieving a "thing" when we haven't defined the "thing" we are attempting to achieve.
Q: May i create similar but multiple around 50. Will it create huge load on callinfo table.
A: As long as the query is efficient, is selecting a smallish set of rows via a suitable index, and runs quickly, I wouldn't expect that query to create huge load, no.
FOLLOWUP
For optimal performance, we are definitely going to want an index with leading column of date.
I'd remove the reference to uniqueid in the query. That is, replace COUNT(c.uniqueid) with SUM(1). The results from those are equivalent (given that uniqueid is guaranteed to be non-NULL) except in the case of no rows, COUNT() will return 0 and SUM() will return NULL.
Since we're dividing by that expression, in the case of "no rows" it's a difference between "divide by zero" and "divide by null". And a "divide by zero" operation will raise an error with some settings of sql_mode. If I divide by COUNT(), I'm going to want to convert a zero to NULL before I do the division
... / NULLIF(COUNT(...),0)
or the more ansi standards compliant
... / CASE WHEN COUNT(...) = 0 THEN NULL ELSE COUNT(...) END
but we can avoid that rigmarole by using SUM(1) instead, then we don't have any special handling for the "divide by zero" case. But what that really buys us is that we are removing the reference to the uniqueid column.
Then a "covering index" for the query will require only two columns.
... ON `callinfo` (`date`,`seconds`)
(i.e. EXPLAIN will show "Using index" in the Extra column, and show "range" for access)
Also, I'm not getting my brain wrapped around the need for CONVERT_TZ.

What does 'Execute failed: (1062) Duplicate entry 'X' for key 'Y'' mean?

I am trying to add X to some table in my DB, but I am getting this error. Even if X doesn't exist in the table, it say it's there. Although X is added to the DB, I want to get rid of this error. I don't know if it's relevant at all, but I'm using Mysqli's prepared statements and this error is printed using $statement->errno." ".$statement->error. Could someone explain this to me? Thanks.
UPDATE: this is the code: X = USER_USERNAME
$stmt = $mysqli->prepare("INSERT INTO USERS (USER_USERNAME, USER_EMAIL, USER_BIRTHDAY, USER_PASSWORD, USER_SALT, USER_IP, USER_ACTIVATION_CODE) VALUES (?,?,?,?,?,INET_ATON(?),?)");
$stmt->bind_param('sssssss',$username,$email,$date,$hashed_password,$salt,$IP,$activation_code);
$stmt->execute();
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
else {
echo "ok";
}
SHOW CREATE TABLE USERS:
CREATE TABLE `USERS` (
`USER_ID` int(11) NOT NULL AUTO_INCREMENT,
`USER_FIRSTNAME` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
`USER_LASTNAME` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
`USER_USERNAME` varchar(30) CHARACTER SET utf8 DEFAULT NULL,
`USER_PASSWORD` varchar(128) CHARACTER SET utf8 DEFAULT NULL,
`LEVEL_ID` int(11) NOT NULL,
`USER_BIRTHDAY` date DEFAULT NULL,
`USER_EMAIL` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
`USER_GENDER` enum('M','W','U') CHARACTER SET utf8 DEFAULT NULL,
`USER_COUNTRY` varchar(30) CHARACTER SET utf8 DEFAULT NULL,
`USER_LOCATION` varchar(30) CHARACTER SET utf8 DEFAULT NULL,
`USER_ADDRESS` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
`USER_HOUSENUMBER` varchar(8) CHARACTER SET utf8 DEFAULT NULL,
`USER_AVATAR` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
`USER_REGISTRATION_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`USER_ACTIVATION_DATE` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`USER_STATUS` enum('REGISTERED','ACTIVE','BANNED','NONACTIVE') CHARACTER SET utf8 DEFAULT NULL,
`USER_BANNED_DATE` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`USER_LATEST_LOGIN` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`USER_EXP` bigint(20) DEFAULT NULL,
`USER_DESCRIPTION` text CHARACTER SET utf8,
`USER_ACTIVATION_CODE` varchar(32) CHARACTER SET utf8 NOT NULL DEFAULT '0',
`USER_SALT` varchar(15) CHARACTER SET utf8 NOT NULL,
`USER_IP` int(10) NOT NULL,
`USER_REMEMBER_KEY` varchar(32) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`USER_ID`),
UNIQUE KEY `USER_USERNAME` (`USER_USERNAME`),
UNIQUE KEY `USER_EMAIL` (`USER_EMAIL`),
KEY `LEVEL_ID` (`LEVEL_ID`)
) ENGINE=MyISAM AUTO_INCREMENT=30 DEFAULT CHARSET=latin1
that's because you are trying to insert or update a value violating a constraint (like PK or UK), for example
if your Table have ID an it's a PK or a Unique Key, you can only have ONE UNIQUE VALUE... it's not possible no repeated....
with a Unique Key you can have Null... but never repeat values in the same column, because you will be breaking the constraint... for more information take a look to http://dev.mysql.com/doc/refman/5.0/es/constraints.html
You already defined a Primary or Unique Key, but again you tried to insert the same value. That time since already there exists a same value, it is not possible to have a redundant value for the primary key or unique key.
It is something like this. Consider you have a table with id and name, with id as primary key. You insert first row as:
INSERT INTO `users` (`id`, `name`) VALUES (1, 'Praveen');
INSERT INTO `users` (`id`, `name`) VALUES (1, 'Kumar');
The second query violates the id uniqueness.
Solution: Try to truncate the table and then run the query again, if it is possible.
Some steps to try
Check for other fields with unique constraints being violated too.
See what query is getting generated.
Put the same query in phpMyAdmin and check.
If you are getting that error then X does exist in the table. Apparently you have not noticed it, but it's there. (Check for things like trimmed spaces, and case sensitivity.)
If you don't get the error in phpMyAdmin then the query you think you are sending is not actually the query you are sending. Most likely you are sending blank for the field, and after you do it once, all further query are using the identical blank value.
Easiest way to check is delete everything from the table (copy it elsewhere first if you want). Then run the query and see what actually got inserted vs. what you expected to get inserted.
You are probably trying to insert a record with the ID (or some other field) 1 set, while such a record already exists in the table. The field that is the primary key must have a unique value for each record.
You could try a simple error check to avoid this error:
$rows = mysql_query("SELECT X from tablenme WHERE X = Y;");
if(mysql_num_rows($rows) > 0){
echo 'Error Messege';
}else{
insert...
}
where X is the primary key or foregin key column and Y is the value to be inserted in that column.
EDIT: Some of the problems that might have caused the problem may be that you have not specified certain columns that can't be null in you insert statement.
Like LEVEL_ID and USER_REMEMBER_KEY. They are set to NOT NULL but the values are not being inserted using the insert statement.
I also don't understand why you are inserting 'sssssss' when the first column is USER_USERNAME and its corresponding value is $username. Do check that too.
SQL Fiddle

Mysql Truncated incorrect DOUBLE value in INSERT query

I know there are lots of bugs like this around here but this query seems to be different, as it's an insert query. Here is the schema for the table card_info:
CREATE TABLE card_info (
card_id mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
card_name_orig varchar(150) NOT NULL,
card_name_html varchar(150) NOT NULL,
card_name_search varchar(150) NOT NULL,
card_name_page varchar(150) NOT NULL,
card_cost varchar(50) DEFAULT NULL,
card_cost_converted tinyint(2) NOT NULL DEFAULT '0',
card_subtype varchar(75) DEFAULT NULL,
card_oracle_text_orig text,
card_oracle_text_html text,
card_power varchar(10) DEFAULT NULL,
card_toughness varchar(10) DEFAULT NULL,
card_loyalty tinyint(1) DEFAULT NULL,
PRIMARY KEY (card_id),
KEY card_name_nd (card_name_search),
KEY card_name_page (card_name_page),
KEY card_cost_converted (card_cost_converted),
KEY card_power (card_power),
KEY card_toughness (card_toughness),
KEY card_loyalty (card_loyalty),
FULLTEXT KEY card_oracle_text_orig (card_oracle_text_orig),
FULLTEXT KEY card_name_search (card_name_search)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
And here is my query:
INSERT INTO card_info (
card_name_orig, card_name_html, card_name_search, card_name_page, card_cost,
card_cost_converted, card_subtype, card_oracle_text_orig, card_oracle_text_html,
card_power, card_toughness, card_loyalty
)
SELECT DISTINCT
d.name_orig, d.name_html, d.name_search, d.name_page, d.cost,
COALESCE(d.cost_converted, 0), d.type_sub, d.oracle_text_orig,
d.oracle_text_html, d.`power`, d.toughness, d.loyalty
FROM card_info_de d
LEFT OUTER JOIN card_info i ON d.name_search = i.card_name_search
WHERE i.card_id IS NULL
AND d.edition_id = 'isd'
ORDER BY (d.collector_number + 0), d.collector_number;
If I perform this query, I'm getting this error:
1292 - Truncated incorrect DOUBLE value: '181a'
Please note that the value 181a is from the column card_info_de.collector_number and it is a VARCHAR(5) field, and that field isn't being inserted to the card_info table anyway, it's just being used in the order clause of the select query.
If I do the query starting from the SELECT only, I can see the correct results are being selected, but when I do the insert, it gives me the error above. Do note that If I remove the ORDER BY clause from the SELECT query, it inserts fine. I don't have a clue what I'm doing wrong.
Thanks in advance.
Just hit the same error myself and it is a bit misleading. I found the answer in another thread:
Error Code 1292 - Truncated incorrect DOUBLE value - Mysql
This message means you're trying to compare a number and a string in a WHERE or ON clause. Either make sure they have similar declarations, or use an explicit CAST to convert the number to a string.
If you turn off strict mode, the error should turn into a warning.
Barmar
So basically check for any of these columns being treated as the wrong data type:
d.name_search
i.card_name_search
d.edition_id
d.collector_number
Try
ORDER BY (d.collector_number + '0'), d.collector_number;
Terrible if true, but quite possible.