Everytime I try to make an insert statement into my dastabase I get a "Incorrect decimal value: 'NULL' for column 'bounty3' at row 1" error. How do I insert a null value into a decimal datatype? Should I just make the default value 0.00?
Incorrect decimal value: '' for column 'bounty3' at row 1 Whole query: INSERT INTO songs (userid, wavURL, mp3URL, genre, songTitle, BPM, insWanted, bounty, insWanted2, bounty2, insWanted3, bounty3, insWanted4, bounty4, insWanted5, bounty5, insWanted6, bounty6, insWanted7, bounty7, insWanted8, bounty8, insWanted9, bounty9, insWanted10, bounty10) VALUES ('12534545', '/audio/wav/jqmrgpfcMichael/135259578210secreason.wav', '/audio/mp3/jqmrgpfcMichael/135259578210secreason.mp3', 'Rock/Funk', 'titlee', '120', 'bass', '20.00', 'guitar', '20.00', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '')
I tried this statement with a NULL value too. Here is the error:
Incorrect decimal value: 'NULL' for column 'bounty3' at row 1 Whole query: INSERT INTO songs (userid, wavURL, mp3URL, genre, songTitle, BPM, insWanted, bounty, insWanted2, bounty2, insWanted3, bounty3, insWanted4, bounty4, insWanted5, bounty5, insWanted6, bounty6, insWanted7, bounty7, insWanted8, bounty8, insWanted9, bounty9, insWanted10, bounty10) VALUES ('12534545', '/audio/wav/jqmrgpfcMichael/143922765110secreason.wav', '/audio/mp3/jqmrgpfcMichael/143922765110secreason.mp3', 'Rock/Funk', 'title', '110', 'bass', '110.00', 'guitar', '20.00', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL')
Oh.. you are trying to insert an empty string '' into bounty3. Replace it with NULL. I have also noticed empty strings for other possible numeric values eg bonty4. You should replace all empty strings with NULL for numeric values.
eg: mysql_query("INSERT INTO empty_number,number VALUES(NULL,1)");
EDIT: HEY HEY get the point, you cannot insert NULL to a numeric value as 'NULL' because this is a string, you should insert as NULL without any quotation marks
use blank, not null, if you want the default value.
I just dealt with this issue in MySql 5.1.61.
If the server is in strict mode, you must enter 0 instead of '' for decimal fields. Disabling strict mode allows you to just do '' to populate a null value.
Thanks, it worked using NULL when it comes empty:
$conn->bindParam(':'.$valor, ( $key[0] ? $key[0] : NULL ), PDO::PARAM_STR);
You can run this query to allow NULL values in 'bounty3' field.
ALTER TABLE songs CHANGE bounty3 bounty3 DECIMAL(10,0) NULL;
Make sure the field type allows for NULL values and that the default is NULL.
Then use:
UPDATE table_name SET date_field=IF('$date_value'='',NULL,'$date_value')
This works for inserts or updates.
I have tried using $date_value = NULL and I have even tried unset($date_value) before inserting or updating, and it never worked on my decimal fields. MySQL always converted them to 0.00. The method above was the only solution that worked for me.
Make sure that the field is "nullable" (does not have NOT NULL in its definition)
Make field's default value NULL.
Ex.: price decimal(12,2) DEFAULT NULL
Now, to test it, store some number, then '' (an empty string) into this field — it should become NULL in the end.
The field is most likely numeric. If the field is numeric then only numbers are accepted. Empty string is not accepted
insert into songs (...,bounty3) values(...,'')
neither the NULL string
insert into songs (...,bounty3) values(...,'NULL')
('NULL' which is just a string, nothing to do with the actual NULL value, so 'NULL' si similar to 'HONEY BEE' if you want).
So if the column is numeric then it will only take numbers. However if the column is NULLABLE then it will accept NULL, too. That means your insert must have
insert into songs (...,bounty3) values (..., NULL)
If you push NULL on such a column and the column has a default value then DEFAULT value will be used instead of the NULL you are pushing.
You need to make sure that your database schema allows NULL values for that column. Run describe <tablename>; in your MySQL client to see what the schema for that table is.
If the schema does not allow null then you can use alter table to change the schema. Make sure you don't specify NOT NULL for that column and you should be fine.
Another option is to make sure that in your source data, the empty cells or fields contain 'NULL' before you import them in MySQL. This way, MySQL will recognize these fields as being really NULL, and won't transform them to 0's.
It worked por me when POST data is received:
...
if ($value == '') {$value = '0.0';}
...
Related
I have three tables defined where always
column 3 is "query", varchar(255) null
column 4 is "tag", varchar(255) null
both columns are the same charset
I submit string $s to column 3 via $wpdb->insert which should do sanitization (but adding extra sanitization to col 3 and col 4 or not adding it does not change anything at all)
function abc($a=null,$tag=null) {
global $wpdb;
$data = array(
'timestamp' => time(),
'query' => sanitize_text_field($a),
'tag' => sanitize_text_field($tag)
);
$format = array('%s','%d');
$wpdb->insert(SS_STATS,$data,$format);
return $wpdb->insert_id;
}
in the template I tried:
abc($s,$s);
abc("$s","$s");
abc("plz save this","$s");
abc("plz save this","plz save this: $s");
In each and every case, column 3 in the db recods 0. In each and every case, column 4 records the correct value just as it is submitted.
Why?
I tried:
changing the name of the column (maybe query is protected)
adding extra sanitization
not adding any sanitization
changing data type to text
changing data type to blob
For every attempt I drop the db and let it recreate.
No change in any case.
How can I save the string in column 3?
The problem was in the format:
$format = array('%s','%d');
$wpdb->insert(SS_STATS,$data,$format);
Removing the formatting solved the issue.
$wpdb->insert(SS_STATS,$data);
I just started learning php and the best way to learn is to work on examples..going through this code I still can't understand what it happening here after looking and relooking in my text books..can someone explain this code to me please?
$_TABLES['the_list'] =
"`t_id` varchar(".T_ID_MAX_CHARS.") NOT NULL default '' UNIQUE, ".
"`tnet` varchar(".TNET_MAX_CHARS.") NOT NULL default '".DEFAULT_TNET."', ".
"`t_version` int unsigned NOT NULL default '0', ".
"`flag_new` bool NOT NULL default '1', ".
"`flag_used` bool NOT NULL default '0', ".
"`comment` tinytext NOT NULL";
what does the syntax "$variable[something]" do?
According to what I see,
there is a variable called _TABLES which is an array
It is defining a key called the_list within this, which contains the text to generate a table in a MySQL database
MORE INFO: http://php.net/manual/en/language.types.array.php
An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments.
array(
key => value,
key2 => value2,
key3 => value3,
... )
PD: You have to be more specific because you're asking something without context.
i'm having the following code:
/** #var DboSource $db */
$db = $this->getDataSource();
var_dump($db->value($open, 'boolean'));
die;
$this->query(
'INSERT INTO foo(`client_id`, `open`, `modified`, `created`) VALUES(:clientId, :open, NOW(), NOW()) ON DUPLICATE KEY UPDATE modified = now();',
[
':clientId' => $db->value($clientId, 'integer'),
':open' => $db->value($open, 'boolean')
]
);
$open is a boolean value, the 'open'-column is defined as tinyint(1). When wrapping $open with $db->value($open, 'boolean') the result is '1', '0' (see the single quotes).
Unfortunately this output leads to a new record with open = false (as '1' is not properly inserted as true)
If I use $db->boolean($open) as option, everything's working correctly.
But I think, $db->value() should do the same job as well?
Looking at when and how DboSource::value() is being used internally, this is the expected behavior. If it wouldn't do what it does, then values wouldn't get prepared properly for Model::save() operations.
DboSource::value() internally passes the "booleanized" value (DboSource::boolean($value, true) this already adds quotes) to PDO::quote(), where the value is going to be quoted anyways no matter what, ie 0, 1, '0', '1', true, or false, it will always return a quoted value, that is '0', '1' or even '' (for false, which is equal to 0).
The problem with your code is, that values passed to the second argument of Model::query() are finally being passed to PDOStatement::execute() (.../DboSource.php#L458), which treats all values as strings and escapes them accordingly, so finally in your query a '1' will end up as '\'1\'', hence the problems.
TL;DR
This seems to be the expected behavior, it's just poorly documented. So when using the second argument of Model::query(), sanitize the values if necessary (ie cast to integers, booleans, strings, etc), but do not escape them, escape them only when you manually insert them in the actual query string (which should however be avoided whenever possible)!
In CodeIgniter, I want to prep a value returned from a form so that if it is a 0, it will actually be inserted as NULL.
I created a function outside of my controller class:
function prep_zero_to_null($int)
{
if ($int == 0)
{
return NULL;
}
else
{
return $int;
}
}
And at the form validation, I do:
$this->form_validation->set_rules('category_id', 'Category',
'required|integer|prep_zero_to_null');
However, CI still tries to insert zeroes as '0' in the database, which breaks one of my foreign key constraints.
Interestingly enough, if I replace NULL by, say, 25 in the prep_zero_to_null function, CI will indeed recognize it and insert 25 instead of '0'. So my prepping function is indeed getting called, but CI won't allow NULL as a result of it and instead converts it to '0'.
How can I achieve what I want?
Edit: For those wondering, the category_id field does allow null:
`category_id` int(10) unsigned DEFAULT NULL
And the exact error is:
INSERT INTO `articles` (`category_id`, `order`, `title`, `text`)
VALUES ('0', '0', 'test', 'test')
^
Should be NULL
Cannot add or update a child row: a foreign key constraint fails
(`db`.`articles`, CONSTRAINT `articles_ibfk_1` FOREIGN KEY
(`category_id`) REFERENCES `categories` (`id`)
ON DELETE SET NULL ON UPDATE CASCADE)
Just looking at this quickly I think the problem is your $int == 0. Is $int an actual 0 type integer or is it a string? In which case the proper check would be $int == '0'.
Codeigniter validation functions doesn't set the field value based on what you return, your validation function should either return TRUE or FALSE to state that something is valid or not.
If you're after changing the value of something, you'll need to accept variable by reference and modify it in the function then you can return TRUE so it passes the validation.
The best solution would be to make the check before inserting the data into database & not relying on the validation library to do this kind of dirty work.
If you want to insert null to the database you need to return a string with the value "null".
function prep_zero_to_null($int) {
return ($int == 0) ? 'NULL' : $int;
}
Have you tried just unsetting the variable. It's a bit ugly, but it should return NULL for the value then.
Tested here.
I submitted an issue at the GitHub bug tracker for CodeIgniter, as this appears to be a bug.
https://github.com/EllisLab/CodeIgniter/issues/2563
Right now, the workaround at model level is the following:
$category_id = prep_zero_to_null($this->input->post('category_id'));
$data = array
(
'category_id' => $category_id,
'order' => $this->input->post('order'),
'title' => $this->input->post('title'),
'text' => $this->input->post('text')
);
Edit: Apparently, this is the right approach, as there should only be strings at validation/controller level.
I'm trying to enter values into a database table using a form and a PHP function. The PHP seems to be fine as the SQL statement it creates looks okay, but the database always throws up an error. This is the SQL statement that my code has generated (with arbitrary values):
INSERT INTO Iteminfo ('itemName', 'itemSeller', 'itemCategory', 'itemDescription', 'itemPrice', 'itemPostage', 'itemBegin', 'itemEnd', 'buynow', 'itemPicture')
values ('gorillaz album', 'ben', 'music', 'new one ', '5.00', '1.00', '2010-03-15 14:59:51', '2010-03-16 14:59:51', '0', 'http://www.thefader.com/wp-content/uploads/2010/01/gorillaz-plastic-beach.jpg')
This throws up an error both when I use the PHP function to evaluate the query and also when I use phpMyAdmin to enter the query manually. However, I can't see anything wrong with it. Can anyone shed some light on this? All of the fields are VARCHAR values, except for itemPrice and itemPostage (which are stored as DECIMAL(4,2)) and the itemBegin and itemEnd, which are stored as DATETIMEs.
Try
INSERT INTO Iteminfo (itemName, itemSeller, itemCategory, itemDescription, itemPrice, itemPostage, itemBegin, itemEnd, buynow, itemPicture)
values ('gorillaz album', 'ben', 'music', 'new one ', '5.00', '1.00', '2010-03-15 14:59:51', '2010-03-16 14:59:51', '0', 'http://www.thefader.com/wp-content/uploads/2010/01/gorillaz-plastic-beach.jpg')
Column names should not be quoted.
Don't quote the column names in the specified list after the table (itemName, itemSeller, etc.)
Per a comment above by middus, The 5.00 and 1.00 should NOT be quoted as they are decimals and not strings.
Your column names shouldn't be strings
try removing '' in column definitions