MySQL insert NULL instead of 0000-00-00 date - php

I have birthday column as a date defined in my table. When i insert a person and left blank birthday field, i get 0000-00-00 and i want to get NULL values. when i insert date as birthday i get date, which is fine.
i tried :
Create table (
birthday DATE NULL,
birthday DATE DEFAULT NULL,
birthday DATE NULL DEFAULT NULL,
);
doesn't work, please a little advice to get NULL instead of 0000-00-00 in my birthday fields.
my php script:
$q = "INSERT INTO users (birthday, other_column, data_registration) VALUES ('$birthday', '$other_column', NOW())
i get no solution yet, any ideea please?

What is in your $birthday?
Suppose you have $birthday = null or $birthday = "null", you will get 0000-00-00. This is because when it's passing to your query, it becomes something like (I believe it's treating your 'null' or null as a string, because you have single quotes around it):
INSERT INTO users (birthday, other_column, data_registration) VALUES ('null', '$other_column', NOW())
Instead try this, which the 2 single quotes around $birthday are removed:
$q = "INSERT INTO users (birthday, other_column, data_registration) VALUES ($birthday, '$other_column', NOW())
Here is an alternative fix:
if ($birthday) {
$q = "INSERT INTO b (birthday, other_column, data_registration) VALUES ('$birthday', '$other_column', NOW())";
} else {
$q = "INSERT INTO b (birthday, other_column, data_registration) VALUES (DEFAULT, '$other_column', NOW())";
}

if you use birthday DATE DEFAULT NULL, in your create statemnt and use
INSERT INTO users (other_column) VALUES ( '$other_column')
You should get null´inbirthday` column.

If you want to EXPLICITLY insert null into the table, then you will need to insert NULL from PHP.
If you want to leave the table to assume its default value, then either OMIT the column from the insert clause entirely, or otherwise use the literal DEFAULT which will apply the default.
e.g.
CREATE TABLE Person
(
Name VARCHAR(20),
BirthDate DATE DEFAULT NULL -- Redundant, since a NULLABLE column will default NULL
);
INSERT INTO Person(Name) VALUES('Joe'); -- Default, NULL
INSERT INTO Person(Name, BirthDate) VALUES('Joe', NULL); -- Explicit Null
INSERT INTO Person(Name, BirthDate) VALUES('Joe', DEFAULT); -- Default, NULL
SqlFiddle example here
If the date in PHP you are inserting is 0000-00-00, then you will need to apply logic in your code to either substitute NULL, DEFAULT for the column, or omit the column (or I guess use a trigger, but this is a hack)

Related

insert data to SQL with default data

I set 3 columns: id(auto increment), names, age(default = 15).
Now if I want to insert data to SQL I can use this below line:
INSERT INTO shoppinglist (name,age) VALUES(?,?)
The first ? = alex and second ? = 22
which will find in the database that the id=1, the name=alex and age=22
Now what I want that if the user inserts only the name without the age, I would like from the age to get the default value, like if the user insert only the name with David, and submit it, I would like to e in DB like id=2 name =David age=15(default)
So is there a way to make the age to get the default if the user didn't insert the age or the age was 0?
create shoppinglist (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`age` int default 15
)
when you make the insertion, it would be like this:
INSERT INTO shoppinglist (name) VALUES ("Alex");
Or
INSERT INTO shoppinglist VALUES (Null, "Alex", DEFAULT);
INSERT INTO shoppinglist (name) VALUES(?)
this query inserts just name and puts the default value 15 for the age
You can use IFNULL function in query:
INSERT INTO shoppinglist (name,age) VALUES(?, IFNULL(?, 15));
The PHP code may look as:
$query = "INSERT INTO shoppinglist (name,age) VALUES(?, IFNULL(?, 15));";
$stmt = $pdo->prepare($query);
$stmt->execute(['Alex', 30]);
$stmt->execute(['Jane', null]);
PHP PDO online fiddle

Does MySQL Insert allow not specifying all fields?

I have two mysql insert statements. The one with all the fields specified in insert statement works fine and insert record to testTable.(Even when http_referer is empty the insert statement insert records to table with referer field empty)
First Insert statement with all fields specified:
mysql_query("INSERT INTO testTable VALUES('$ID','".$_SERVER['REMOTE_ADDR']."',NOW(),'Page1','".$_SERVER['HTTP_REFERER']."')");
The problem is with second insert statement that doesn't insert any record to testTable!
Could you guys tell me why my second insert statement doesn't insert any record to testTable?
Second insert Statment:
mysql_query("INSERT INTO testTable VALUES('$ID','".$_SERVER['REMOTE_ADDR']."',NOW(),'Page1')");
Create Table:
CREATE TABLE IF NOT EXISTS `testTable` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`ip` varchar(32) DEFAULT NULL,
`date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`Title` varchar(32) NOT NULL,
`Ref` varchar(250) NULL default '',
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1784 ;
Yes, by using a column list.
$sql = "INSERT INTO table (`ip`, `date`, `Title`) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW(), 'Page 1')";
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which.
You can choose to specify which columns you want to insert into in an insert statement.
$sql = "INSERT INTO testTable(ID, ip, date, Title)
VALUES('$ID','".$_SERVER['REMOTE_ADDR']."',NOW(),'Page1')";
Additionally, please don't use mysql functions as they are deprecated now. Use MySQLi, or PDO
You have to specify the fields with the second query. If you're not going to insert every column, in the order of the columns, then you have to specify the column names.
INSERT INTO table (column1, column2, columns3) VALUES ('$value1', '$value2', '$value3');
You can use a column list or SET syntax
Column list:
INSERT INTO table (column1, column2) VALUES ('$value1', '$value2');
SET syntax:
INSERT INTO table SET column1 = '$value1', column2 = '$value2';
In first query error not comes because you are specifying all column and fieleds.If any filed is auto increment or by default null you should mention all the column name along with values in insert query accepting null of auto increment field
this are demo with
All field value
insert into testtable values (1,"127.1.1.0",curdate(),"test 1","default");
Without Default value
insert into testtable (id,ip,date,title) values (1,"127.1.1.0",curdate(),"test 1");
without auto increment field
insert into testtable (ip,date,title) values ("127.1.1.0",curdate(),"test 1");

PHP: use id to another column

Ok, so i have a normal query that inserts to the database.
mysql_query("INSERT INTO users_pm_in (uID, msg) VALUES ('$uID', '$msg')");
Now this table has also a column called "id" with auto_increment & primary key.
When it inserts it auto makes number for the column in the row. Now I want this number, and put it in column dialog, in the same row. So the inserted row have the same number/id in "id" and "dialog". How can i do that?
Not sure if this can be done in one query (or why you even want to do this), but you can use this:
mysql_query("INSERT INTO users_pm_in (uID, msg) VALUES ('$uID', '$msg')");
mysql_query("UPDATE users_pm_in SET dialog = id WHERE id = '".mysql_insert_id()."');
Be sure to escape the variables properly also.
I think it would be easier to remove the autoincrement and add the id+dialog value yourself.
Check out mysql_insert_id()
You can do this, altough it's not very efficient...
Supose you have this table:
CREATE TABLE `test` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`a` INT(10) NULL DEFAULT '0',
`b` INT(10) NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
ENGINE=MyISAM
ROW_FORMAT=DEFAULT
You can perform the following query:
INSERT INTO test (a, b) SElECT IFNULL((MAX(id) +1),1), 200 FROM test;
Notice that "200" is some random value that will be inserted on "b" column.

mysql insert problem

ive got a really weird problem. i have no clue why its not working. i create an user and get the id and insert a row based on that id in another table. the row gets inserted with that id but the other values however for that row are not inserted!
$user_id = mysqli_insert_id($this->connection);
$query = "INSERT INTO selections
(user_id, language_id, country_id, region_id, city_id, gender_id, age_id, category_id)
VALUES ($user_id, 1, 1, 0, 0, 0, 20, 0)";
so the user_id gets inserted, but not the other values (they are all 0 in the table). i have really checked the columns and deleted all foreign keys to debug this problem. but i have no clue at all.
the columns are all INT. the weird part is sometime when i replace $user_id with a literal number it works, sometimes it doesnt. but the row is always created. and i have checked that $user_id is an integer.
i know this is a hard problem and that it can be caused of a lot of things, but i have tried to solve this tiny issue for 3 hours now. so would be great if someone just gave me something i could do to debug this problem.
UPDATE: even when i have set default values and just insert the first column (user_id) it doesnt work. every other field is 0. So weird!
| selections | CREATE TABLE `selections` (
`user_id` int(11) NOT NULL,
`language_id` int(11) NOT NULL DEFAULT '1',
`country_id` int(11) NOT NULL DEFAULT '1',
`region_id` int(11) NOT NULL DEFAULT '0',
`city_id` int(11) NOT NULL DEFAULT '0',
`gender_id` int(11) NOT NULL DEFAULT '0',
`age_id` int(11) NOT NULL DEFAULT '0',
`category_id` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
$query = "INSERT INTO selections
(user_id)
VALUES ('$user_id')";
the user_id shows 178 and other fields are 0:(
UPDATE:
It worked in the sql command line. but not in php. but mysqli generated no error and the row was indeed inserted but why are the other fields 0?
ANSWER: My fault. i had a jquery script that changed it back to 0 0 0 0 0 0 0. There's a lot of AJAX on my page so it was tricky to find it...sorry my bad!
When you run into situations like this, print the query to screen before it is executed:
$query = "INSERT INTO ...";
echo $query
Try:
$query = "INSERT INTO selections
(user_id, language_id, country_id, region_id, city_id, gender_id, age_id, category_id)
VALUES
({$user_id}, 1, 1, 0, 0, 0, 20, 0)";
You need to wrap PHP variables in {} when referencing them in SQL string statements.
Use Your DEFAULT Constraints
If you have defaults then you don't need to set the values in your INSERT statement:
INSERT INTO selections
(user_id)
VALUES
({$user_id})
Referencial Integrity
You're getting the last inserted id and using it in a subsequent insert into another table, but you don't have a foreign key defined on the user_id column to ensure that the value going into that column actually exists in the other table. If you provide the name of the table & column you are getting for your last insert id, I'll provide the ALTER TABLE statement.
$query = "INSERT INTO selections
(user_id, language_id, country_id, region_id, city_id, gender_id, age_id, category_id)
VALUES ('$user_id', 1, 1, 0, 0, 0, 20, 0)";
Single quotes around $user_id might do it.

counting the number of updates to a row in my mysql table

I have a simple mysql DB and use this PHP code to update it.
mysql_query("REPLACE INTO `$db_table` (username, live, datetime, ip)
VALUES ('$username', '1', '$timeofentry', '$ip')");
I use REPLACE INTO along with a primary key on "username" to let users bump themselves to the top of the most recent list...
I would like to add a bump count. The number of times an entry has been updated (or "replaced into").
How would I go about doing this?
Thanks a lot!
You can use INSERT ... ON DUPLICATE KEY UPDATE which performs an actual update of existing rows.
$mysql = mysql_connect(..
...
$username = mysql_real_escape_string(...
$ip = mysql_real_escape_string(...
...
$query = "
INSERT INTO
`$db_table`
(username, live, datetime, ip)
VALUES
(
'$username',
'1',
'$timeofentry',
'$ip'
)
ON DUPLICATE KEY UPDATE
ip = '$ip',
bumpCount = bumpCount + 1
";
$result = mysql_query($query, $mysql);
First, you need to add another column to your table to keep the count.
Second, you should probably use the UPDATE statement instead of REPLACE.
REPLACE will actually delete the row, then INSERT a new one which isn't very efficient.
UPDATE `$db_table` SET datetime = NOW(), ip = '$IP',
bumpCount = bumpCount + 1 WHERE username = '$username' LIMIT 1;
#dot
You'd define your bumpCount field as another column in the table. I'd recommend setting it to a default value as well.
Then your table definition would be sometime like:
CREATE TABLE my_table
(username varchar(255) not null primary key,
live int,
datetime datetime not null,
ip varchar(15) not null,
bumpCount int unsigned not null default 1);
And your insert/update would be something like:
INSERT INTO my_table (username,live,datetime,ip)
VALUES
('$username',1,now(),'$ip')
ON DUPLICATE KEY UPDATE datetime=now() ip='$ip', bumpCount=bumpCount + 1;

Categories