What I'm asking is whether when inserting a row in a MySQL database the columns that are null need to be included. For instance, when I use phpMyAdmin to insert a row, it will do something like this:
INSERT INTO table
(
`col1`,
`col2`,
`col3`,
`col4`
)
VALUES
(
'value1',
NULL,
NULL,
'value2'
)
Assuming the fields are null by default, can I remove columns and NULL values from the insert statement?
by default, when you create column it is nullable (unless you have set NOT NULL on it). so when you want to insert record for specific columns only, you can omit that column and the values for it are automatically null.
INSERT INTO table (`col1` ,`col4`)
VALUES ('value1','value2')
you can remove them.
if there is a default value - you will get that instead.
If the column name is also omitted, yes: the default value1 will be assumed.
1 NULL is usually - but not always! - the default value for nullable columns. The schema must be consulted to verify this assumption.
Related
A db table consists of 3 columns. But I want to insert a value to one column and I want the other 2 to remain empty. Like database has three input column- roll, date, time, I want only to insert roll. My query:
insert into tableName(roll) values ('$_POST['roll'])
But I am getting the error message ( Field attn_time doesn't have a default value41 ). What would be the correct query?enter image description here
database table
You need to alter your database table by giving a default value to your attn_time column.
Example:
ALTER TABLE table_name MODIFY COLUMN column_name VARCHAR(255) NOT NULL DEFAULT '';
You achieve this in two ways:
1) Go to your phpmyadmin/mysql and change your columns(attn, attn_time) "Null" property to "Yes". This will allow null value to store in column if non value given.
[You can find "Change" in "Structure" tab in phpmyadmin]
2) You can change your query to
insert into tbl1 (roll, attn, attn_time) values ('$roll', null, null)
OR
insert into tbl1 (roll, attn, attn_time) values ('$roll', '', '')
You can use :
$roll=$_POST['roll'];
add your validation :
insert into tableName(roll) values ('$roll');
So I have a PHP form to add a row to a database. If any of the unrequired fields are empty, the default value for that field should be used.
I tried to implement this with MySQLi like this:
$required = $_POST["required"];
$unrequired = isset($_POST["unrequired"])?$_POST["unrequired"]:"DEFAULT(`Unrequired`)";
$sql = $mysqli->prepare("INSERT INTO `table` (`Required`,`Unrequired`) VALUES (?,?)");
$sql->bind_param("is",$required,$unrequired);
$sql->execute();
But when I try to get the value of the unrequired field using SELECT unrequired FROM table WHERE required = 33, I get DEFAULT(`Unrequired`) instead of the default value of the column for varchar columns, and 0 for int and double columns.
Is this problem caused by PHP, or MySQL?
NOTE: Some of the unrequired fields are nullable and some are not. Those which aren't nullable have a set default value. int and double fields' set default value is 1, the rest are nullable.
Can't you just set default value in your database structure. Below you can see an example;
CREATE TABLE example_table
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Address varchar(255), DEFAULT 'unrequired'
City varchar(255) DEFAULT 'Unrequired'
)
When you create your table like that you are good to go. You can also alter your table
ALTER TABLE example_table
ALTER City SET DEFAULT 'Unrequired'
Alright, I think I figured out the problem.
Since I am using prepared statements, every parameter that I put in the reslting SQL query statement will be converted into safe strings, ints or doubles, so I suppose expressions like DEFAULT(column) will be re-interpreted as "DEFAULT(column)", and will be considered as strings.
Although not a very safe solution, I've considered using not prepared statements, that is concat every parameter and using DEFAULT like in here. To make the queries safer, I'll use real_escape_string() for strings.
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.
How do you set allow mySQL to auto increment a row in mySQL when using php? I have set the link_id column as auto_increment using phpMyAdmin but I do not know how to get the row to auto increment when using PDO.
$preparedStatement = $con->prepare('INSERT INTO link (link_id, category, link_desc, link_url) VALUES (:link_id, :category, :link_desc, :link_url)');
$preparedStatement-> execute(array(':link_id' => **AUTO INCREMENT Field in mySQL**, ':category' => $category,':link_desc' => $link_desc,':link_url' => $link_url));
Thanks for the help in advance!
You don't have to do anything special with PHP, but there are several ways in MySQL. One is to use a falsey value or null:
INSERT INTO link (<columns>) VALUES (null, category...
Just exclude the parameter in PHP.
You can also specify columns to insert, and if you leave off the auto_increment key, it gets auto incremented:
INSERT INTO link (category, link_desc...)
You can fill the AUTO_INCREMENT column at INSERT statement with any value ...
MySQL automatically will override AUTO_INCREMENT column value that are defined into your statement and handle with new value correctly.
In console mode it generates a warning if the value wasn't set correctly, but in PHP i think it will be ignored.
I need to do something simple - insert a row into MySQL (with PHP) but without values. The MySQL table will already have the default values it needs, so I don't need to insert any values. How would the insert statement look without values to insert?
INSERT INTO my_table VALUES ()
In SQL Server it is like this.
insert into TableName default values
The proper way is to provide an empty values list and let the fields take their default values implicitly:
INSERT INTO `table` () VALUES();
Alternatively you can use the DEFAULT keyword:
INSERT INTO `table` (`Col1`, `Col2`, ...) VALUES(DEFAULT, DEFAULT, ...);
Or (assuming you're giving values for all the columns) just:
INSERT INTO `table` VALUES(DEFAULT, DEFAULT, ...);
All the required information can be found in the documentation for INSERT:
If you do not specify a list of column names for INSERT ... VALUES or
INSERT ... SELECT, values for every column in the table must be
provided by the VALUES list or the SELECT statement. If you do not
know the order of the columns in the table, use DESCRIBE tbl_name to
find out.
[..]
If you are not running in strict SQL mode, any column not explicitly
given a value is set to its default (explicit or implicit) value. For
example, if you specify a column list that does not name all the
columns in the table, unnamed columns are set to their default values.
Default value assignment is described in Section 10.1.4, “Data Type
Default Values”. See also Section 1.8.6.2, “Constraints on Invalid
Data”.
[..]
Use the keyword DEFAULT to set a column explicitly to its default
value. This makes it easier to write INSERT statements that assign
values to all but a few columns, because it enables you to avoid
writing an incomplete VALUES list that does not include a value for
each column in the table. Otherwise, you would have to write out the
list of column names corresponding to each value in the VALUES list.
[..]
If both the column list and the VALUES list are empty, INSERT creates
a row with each column set to its default value:
INSERT INTO tbl_name () VALUES();
[..]
In strict mode, an error occurs if any column doesn't have a default
value. Otherwise, MySQL uses the implicit default value for any
column that does not have an explicitly defined default.
You can use default values:
insert YourTable default values