Does MySQL Insert allow not specifying all fields? - php

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");

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

MySQL insert NULL instead of 0000-00-00 date

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)

MySQLi does not return error code

In my MySQL database I have a table "table1" with unique constraint set on column "name" - I want to prevent duplicate names.
If there's already name 'John' in table this code:
$db=new mysqli(...);
$sql="INSERT INTO table1 SET id=10,name='John'";
if(!$db->query($sql))
{
if($db->errno==1062)
{
throw new InsertNonUniqueException(...);
}
else
{
throw new InsertException(...);
}
}
should throw InsertNonUniqueException() (my own exception). Instead, it throws InsertException().
Execution of query returns false and execution enters the if() loop. Also $db->row_affected is -1 but problem is that $db->errno is always O (it should be 1062)!!! So I can't detect that my insert error was caused by violating unique key constraint on name column!
I don't know why mysqli does not return 1062 code when unique key constraint violation occurs!
I can't leave a comment, thus going to ask you here.
Please provide the result of SHOW CREATE TABLE table1;
I can't reproduce your problem using your code and next table:
CREATE TABLE `table1` (
`name` varchar(11) COLLATE utf8_unicode_ci NOT NULL,
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Am I the only one around here that thinks you have an error in your SQL syntax?.. There is no room for SET in INSERT INTO, because you can only use SET in UPDATE statements (assuming you habe MySQL in version 5.5 or below).
INSERT INTO syntax is like the following (as described in the docs):
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE col_name=expr, ... ]
OR
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
Try it like this:
<?php
$sql="INSERT INTO table1 (id, name) VALUES ('10', 'John')";
...
step 1
make sure that the table has a unique key
SHOW CREATE TABLE table1
expected result
CREATE TABLE `table1` (
`id` INT(11) default NULL,
`name` varchar(11) COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci
if there is UNIQUE KEY name (name) we have a unique key
step 2
try to change your code
$db = new mysqli(...);
// first insert
if( !$db->query("INSERT INTO table1 (id, name) VALUES (10, 'John')") ) {
throw new Exception($db->error);
}
// second insert (for me raise: Duplicate entry 'John' for key 'name')
if( !$db->query("INSERT INTO table1 (id, name) VALUES (11, 'John')") ) {
throw new Exception($db->error);
}
Please, try these two steps
Side note: if you have name and id as duplicates, only the first duplicate encountered will be returned in the message.
The only issue i have with your code is that:
having setup your table and columns.
I setup a unique index on the table. I did .. stuff on a two column table that ensure it works.
You missed the 'new'
keyword when you 'throw exceptions'.
this is the only error with your posted code that i could find.
i.e: throw new Exception('Division by zero.'); // example taken from PHP manual.

update then replace dies

If there is a row for user_id then I want to update, if not insert (but I was told to use replace). In the table there is id (which is primary key, auto inc) and user_id (index, session relates to). I have a form that when the data is changed it should be changed in the database for that particular user in session, otherwise it is just added for that particular user in session
if (empty($err)) {
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
$query="UPDATE thesis SET thesis_Name ='$thesis_Name',
abstract='$abstract' WHERE id='$_SESSION[user_id]'
IF ROW_COUNT()=0
REPLACE INTO thesis (thesis_Name,abstract)VALUES ('$thesis_Name', '$abstract')
";
mysql_query($query) or die();
// query is ok?
if (mysql_query($the_query, $link) ){
// redirect to user profile
header('Location: myaccount.php?id=' . $user_id);
}
With this the page just dies.
EDIT:
`thesis` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`thesis_Name` varchar(200) NOT NULL,
`abstract` varchar(200) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
)
Thanks so much
You don't need to do the UPDATE first - REPLACE handles all of this for you. From the MySQL manual:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. See Section 13.2.5, “INSERT Syntax”.
Therefore, so long as id is a unique key in your thesis table, the only SQL you need is:
REPLACE INTO thesis (id, thesis_Name, abstract)
VALUES ('$_SESSION[userid]', '$thesis_name', '$abstract');
There are a few things in your code that pose problem. First you don't have to do an insert and a replace in the same query : replace will insert if there is no row to replace (besides, I'm not even sure the sql syntax you're using is correct)...
Then you do a mysql_query($query) or die() which is probably where your code dies (maybe due to the fact that the sql syntax you used could be incorrect).
Right after that, you do a mysql_query again, which would reexecute the query a second time. Anyway, if your query didn't work, your code would have died on the previous line...
What you could do would be
$query = "REPLACE INTO blablabla";
if (!mysql_query($query))
echo "the query failed";
else header ("location:blabla");
but your query should mention for which user_id you want to update like this
REPLACE INTO thesis (id, thesis_Name, abstract)
VALUES ('{$_SESSION[userid]}', '$thesis_name', '$abstract');
INSERT
INTO thesis (id, abstract, thesis)
VALUES ('$_SESSION[user_id]', '$abstract', '$thesis_Name')
ON DUPLICATE KEY
UPDATE
abstract = VALUES(abstract),
thesis_Name = VALUES(thesis_Name)
You can do it with prepared statements.You can see an example sql ;
DROP PROCEDURE IF EXISTS `UPDATETHESIS`
|
CREATE PROCEDURE `UPDATETHESIS` (IN _id VARCHAR(50), IN _thesis_name VARCHAR(50), IN _abstract VARCHAR(50))
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY INVOKER
IF EXISTS (SELECT * FROM thesis WHERE id = _id)
BEGIN
UPDATE thesis SET thesis_Name = _thesis_name,
abstract = _abstract WHERE id = _id
END
ELSE
BEGIN
INSERT INTO thesis (thesis_Name,abstract) VALUES (_thesis_name, _abstract)
END
You can call this like CALL UPDATETHESIS(userid, thesis_name, abstratc);

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.

Categories