Wrong value default ENUM Mysql type - php

as i see every where even in here :
From the MySQL manual:
If an ENUM column is declared to permit NULL, the NULL value is a
legal value for the column, and the default value is NULL. If an ENUM
column is declared NOT NULL, its default value is the first element of
the list of permitted values.
But in my database is not like this !!!! Why ?
this is one of field structure :
`dead` enum('0','1') NOT NULL DEFAULT '0';
but why all data in the dead field is null ???
and if i chose that type to enter a value this will be list :
()Empty
(0)
(1)
Why always null is there ?
and another thing is when i use query like this :
UPDATE TABLE SET dead = 0 -> result : dead = null
UPDATE TABLE SET dead = 1 -> result : dead = 0
UPDATE TABLE SET dead = 2 -> result : dead = 1
Best Regards.

It is not clear what you are asking for.
Here is fiddle: http://sqlfiddle.com/#!9/8b24d0/1
As we can see when dead is not set in INSERT query:
insert into table1 (id) values (4);
mysql put there your default value '0' and that is what you were expecting I guess.
I don't know what version of mysql do you use, but in my fiddle it is clear that mysql doesn't allow to:
UPDATE table1 SET dead = 0;
Since it is enum, it only allows:
UPDATE table1 SET dead = '0';
And that is correct and expected behavior since you choose ENUM type for the column. So I can't reproduce described in OP behavior. If anybody else can?
GUESS I guess that you are trying to convert existing table column with existing data in that column and stuck. So to run alter table you should fix data first like:
UPDATE table1 SET dead='0' WHERE dead IS NULL;
So once you get data fixed you can try ALTER TABLE to set DEFAULT.

Related

PHP empty string error for mysql date column with null value

I have an HTML form with an input field (type="date") and a mysql DB with a column with datatype "date" that accepts null when I do the query directly in phpmyadmin.
Also when I select a date in my html form (using browser default date picker) the query runs correctly. But when I leave the mentioned input blank, the following error is shown "Incorrect date value: '' for column 'received_date'.
Any help to get rid of this issue is appreciated.
Here are the sql and DB/Table schema:
CREATE TABLE customer.tbl1 ( id INT NOT NULL AUTO_INCREMENT , usrname
VARCHAR(32) NOT NULL , received_date DATE NULL DEFAULT NULL , PRIMARY
KEY (id)) ENGINE = MyISAM;
$sql = "INSERT INTO tbl1 (usrname, received_date) VALUES ('$usrname',
'$received_date')";
Thank you all.
The following solved the issue:
if (empty($received_date)) {
$received_date= 'NULL';
}
However, before posting the problem here I tried this (if condition) with NULL without the single quotes but It didn't work. Now the single quotes solved the issue.
The answer depends on your application: Is Null a valid value for your data?
If that's ok, then update your database schema to allow Null values (https://stackoverflow.com/a/35963275/3341745).
If you don't want this value to be Null, then the database check is doing its job. In this case, you should validate the data on the web page before the user is allowed to submit it (https://www.w3schools.com/js/js_validation.asp).

Migrating old table structure to new found enum is not working

I am using this alter statement and NULL value columns are not transferred as 'Male' still remains NULL:
alter table users modify gender ENUM('Male', 'Female') NOT NULL default 'Male';
Why is it not working? Do I need to do it in some other way?
Default value works only in case of New row insertion.
Although you can set these NULL values to default rows using single update command after the alter command to enum as:
UPDATE users SET gender=default where gender is NULL;
Thanks

TIMESTAMP on UPDATE doesn't work with PHP

I have a feeddate column with the info below..
type : timestamp
attributes : on update CURRENT_TIMESTAMP
default : CURRENT_TIMESTAMP
and when I used PHP to INSERT INTO the rows with this code ..
$badgefeed = "INSERT INTO d VALUES ('','".$userID."','Badge','','".$badgeNAME."','".$badgeTYPE."','".$badgelv."','','')";
$badgefeedQ = mysql_query($badgefeed);
(feeddate is on the last column that NULL)
This feeddate doesn't update and be like 0000-00-00 00:00:00
but it's gonna work when I used PHP to UPDATE something that already had in the table.
Did I do anything wrong with my feeddate structure or the INSERT code is incorrect ?
Your query should be:
$badgefeed = "INSERT INTO d VALUES ('','".$userID."','Badge','','".$badgeNAME."','".$badgeTYPE."','".$badgelv."','')";
Don't use any value for the last column as you are using the timestamp as default value in MySQL. Just omit the last (blank) value from your query. In such a way, value for the concerned column will be considered null and thus default timesamp will will be used.
Insead of '' use null.
This way, mysql manages the value itself.
If you specify any value, the server will take your value, regardless other triggers, settings.
If you don't include the column in the insert statement or leave it blank (null), it will get set by the server, according to the defaults. In this case the default being on update CURRENT_TIMESTAMP

Field doesn't have a default value

I'm trying to follow along to https://netbeans.org/kb/docs/javaee/ecommerce/connect-db.html this for an assignment but I'm using my own entity relationship diagram in mySQL workbench.
As can be seen here https://www.flickr.com/photos/93791690#N02/23076476850/in/dateposted-public/
But when I try and follow what is said on the Netbeans site Delete 'select * from category' and enter the following SQL statement:
INSERT INTO `category` (`name`)
VALUES ('dairy'),('meats'),('bakery'),('fruit & veg');
But try with my own:
INSERT INTO `book` (`price`) VALUES ('20.0');
INSERT INTO `book` (`author_name`) VALUES ('author_name');
I keep getting errors saying
Error code 1364, SQL state HY000: Field 'author_name' doesn't have a default value
Line 1, column 1
Error code 1364, SQL state HY000: Field 'price' doesn't have a default value
Line 2, column 1
Execution finished after 0 s, 2 error(s) occurred.
Can someone please help me to start going in the right direction
Unless you want to insert two lines,
INSERT INTO `book` (`price`, `author_name`) VALUES ('20.0', 'author_name');
is likely what you want to do. The inserts trying to set just one column are failing because the other column has no default value. All columns which do not have a default value need to be set in an insert. If you intended to insert two rows here, then you'll need to make sure you specify values for both columns in each insert or ALTER your table so that the column has DEFAULT values. For example,
ALTER TABLE `book` MODIFY `author_name` varchar(200) DEFAULT '';
changing the size of the varchar to be whatever your author_name column is and replacing the empty string '' with whatever you want the default to be.

Change Column to Auto_Increment

I asked this question a little earlier today but am not sure as to how clear I was.
I have a MySQL column filled with ordered numbers 1-56. These numbers were generated by my PHP script, not by auto_increment.
What I'd like to do is make this column auto_incrementing after the PHP script sets the proper numbers. The PHP script works hand in hand with a jQuery interface that allows me to reorder a list of items using jQuery's UI plugin.
Once I decide what order I'd like the entries in, I'd like for the column to be set to auto increment, such that if i were to insert a new entry, it would recognize the highest number already existing in the column and set its own id number to be one higher than what's already existing.
Does anyone have any suggestions on how to approach this scenario?
I'd suggest creating the table with your auto_increment already in place. You can specify a value for the auto_inc column, and mysql will use it, and still the next insert to specify a NULL or 0 value for the auto_inc column will magically get $highest + 1 assigned to it.
example:
mysql> create table foobar (i int auto_increment primary key);
mysql> insert into foobar values (10),(25);
mysql> insert into foobar values (null);
mysql> select * from foobar;
# returns 10,25,26
You can switch it to MySQL's auto_increment implementation, but it'll take 3 queries to do it:
a) ALTER TABLE to add the auto_increment to the field in question
b) SELECT MAX(id) + 1 to find out what you need to set the ID to
c) ALTER TABLE table AUTO_INCREMENT =result from (b)
MySQL considers altering the AUTO_INCREMENT value a table-level action, so you can't do it in (a), and it doesn't allow you to do MAX(id) in (c), so 3 queries.
You can change that with a query, issued through php, using the mysql console interface or (easiest) using phpmyadmin.
ALTER TABLE table_name CHANGE old_column_name new_column_name column_definition;
ALTER TABLE table_name AUTO_INCREMENT = highest_current_index + 1
column_definiton:
old_column_definition AUTO_INCREMENT
More info:
http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
http://dev.mysql.com/doc/refman/5.1/en/create-table.html
EDIT
Always use mysql_insert_id or the appropiate function of your abstraction layer to get the last created id, as LAST_INSERT_ID may lead to wrong results.
No, stop it. This isn't the point of auto_increment. If you aren't going to make them ordered by the id then don't make them auto_increment, just add a column onto the end of the table for ordering and enjoy the added flexibility it gives you. It seems like you're trying to pack two different sets of information into one column and it's really only going to bite you in the ass despite all the well-meaning people in this thread telling you how to go about shooting yourself in the foot.
In MySQL you can set a custom value for an auto_increment field. MySQL will then use the highest auto_increment column value for new rows, essentially MAX(id)+1. This means you can effectively reserve a range of IDs for custom use. For instance:
CREATE TABLE mytable (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
col1 VARCHAR(256)
);
ALTER TABLE mytable AUTO_INCREMENT = 5001;
In this schema all ids < 5001 are reserved for use by your system. So, your PHP script can auto-generate values:
for ($i=1; $i<=56; $i++)
mysql_query("INSERT INTO mytable SET id = $i, col1= 'whatevers'");
New entries will use the non-reserved range by not specifying id or setting it to null:
INSERT INTO mytable SET id = NULL, col1 = 'whatevers2';
-- The id of the new row will be 5001
Reserving a range like this is key - in case you need more than 56 special/system rows in the future.
ALTER TABLE <table name> <column name> NOT NULL AUTO_INCREMENT
More info:
AUTO_INCREMENT Handling in InnoDB
Server SQL Modes

Categories