Hi i am importing a csv through a script
the table structure is as below
`contact_id` int(11) NOT NULL auto_increment,
`contact_first` varchar(255) character set latin1 default NULL,
`contact_last` varchar(255) character set latin1 default NULL,
`contact_email` varchar(255) character set latin1 default NULL,
PRIMARY KEY (`contact_id`)
and the data in csv is like this
Jim,Smith,jim#tester.com
Joe,Tester,joe#tester.com
and the query i am using for insert is as below
mysql_query("INSERT IGNORE INTO contacts (contact_first, contact_last, contact_email) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."'
)
");
i have made use of ignore function in the query but it doesnot work and it keeep on onserting the same value
The IGNORE keyword will only have your desired impact on duplicate rows.
A row will only be recognized as a duplicate if you have a primary key or unique key on the appropriate columns.
You haven't really explained exactly what the issue is, but I suspect you might want to create a unique key on the contact_email column to prevent duplicates from being inserted.
I would also suggest at a minimum using mysql_escape_string instead of addslashes to ensure the strings are encoded correctly.
There will likely be comments on the fact that the mysql_* functions are deprecated so you should look into PDO or mysqli_* functions.
If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead
Refer DOCS
The use of IGNORE is :
If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.
in your case you are inserting three values which are same but as the ID is auto incremental which will insert new record with same values which is obvious.
If you want to prevent it from inserting in to the database you have to add unique index to one of the other column
hope it will help!
Related
I started to a new php script, and I used for the first time the DATATIME option in mysql. I think it makes the problem.
My sql table is :
id int(6) auto_increment,
name varchar(40) not null,
pseudo varchar(40) not null,
email varchar(40) not null,
password varchar(40) not null,
plan varchar(40) not null,
date DATETIME DEFAULT CURRENT_TIMESTAMP,
points int(6) not null,
primary key(id,name,pseudo,email,password,date,points,plan)
When I try to execute this query:
insert into users(NULL,"name","pseudo","email#email.com","Pass1919",NULL,
"100");
This error displays :
ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'NULL,
"name","pseudo","email#email.com","Pass1919",NULL,"100")' at line 1
try this..
insert into users(name,pseudo,email,password,paln,date,poits)
values("name","pseudo","email#email.com","Pass1919",NULL, "100");
As others have said, and
insert into users(name,pseudo,email,password,paln,date,poits)
values("name","pseudo","email#email.com","Pass1919",'', NULL, "100");
plan varchar(40) not null,
What they missed is plan is not null, and either enter null for date or I would prefer to just omit it completely.
insert into users(name,pseudo,email,password,paln,poits)
values("name","pseudo","email#email.com","Pass1919",'', "100");
If you count the fields and the inputs in some of the above responses they are not equal. The field list is optional in the insert but i would use them, for readability and to make sure you have the order and number of inputs correct.
Last thing change to the primary key, to just the auto increment field, if you need other compound indexes, you should add them separate and make unique as your requirements would require. Primary keys should be a surrogate key, as defined this way
the value is unique system-wide, hence never reused
the value is system generated
the value is not manipulable by the user or application
the value contains no semantic meaning
the value is not visible to the user or application
the value is not composed of several values from different domains.
The other keys should relate to the data, and like i said if you need a compound unique key, or just a unique filed like email make it separate from the primary one.
You have to use the keyword values:
insert into users values(NULL,"name","pseudo","email#email.com","Pass1919",NULL,
"100");
Don't pass first parameter as NULL, as you already specified it as primary key and auto increment also.
use this
insert into users values("name","pseudo","email#email.com","Pass1919",NULL, "100");
Try this
INSERT INTO users(
`name`,
`pseudo`,
`email`,
`password`,
`plan`,
`points`
)
VALUES (
NULL,
'name',
'pseudo',
'email#email.com',
'Pass1919',
NULL,
'100');
try to add your table field name which you want to insert values with values keyword. also auto increment id can not be NULL if you dont want to send id, date
values leave that it both will collect values auto with increment and current timestamp
insert into users(name,pseudo,email,password,plan,points) values ('name','pseudo','email#email.com','Pass1919','','100');
Also, when you are dealing with integers you do not need to enclose it in quotations when inserting so you can do
insert into users(name,pseudo,email,password,plan,date,points)
values("name","pseudo","joe.bloggs#mydomain.com","S3CuR3", "PLAN", "2014-06-26", 100);
I currently have a database called Spreadsheet with 2291 rows, each with 6 columns.
I also have a .csv file with 1000 more of these rows with the same 6 columns, though three of them are set default to NULL (same as some of the data in my database, meaning, some are set to NULL as default too). I was trying to import them (not replace) into the existing database.
The first columns is the primary key, and I know both the .csv and database do not have duplicate primary keys. The primary key looks something like this: 0015000000b0Y2u
My question is: how do I import these 1000 more rows (which come with unique primary keys themselves) into the pre-existing 2291 rows without getting the #1062 error?
SQL query:
INSERT INTO `Spreadsheet` ( `accountID` , `accountName` , `website` , `rating` , `imageURL` , `comments` , `category` )
VALUES (
'0015000000b0Y3z', 'Kittredge and Associates Inc', 'kittredgeandassociates.com', NULL , 'kittredgeandassociates.com.jpg', NULL , NULL
)
MySQL said:
#1062 - Duplicate entry '0015000000b0Y3z' for key 'PRIMARY'
Attached above is the #1062 error I have been receiving, despite being 100% sure that I do not have a duplicate key for PRIMARY.
I do not want to have mySQL autoincrement, as I have looked into that, and it is not the solution I am looking for.
I have tried changing the duplicate entry offender key, but to no avail, same error. Could someone lend me a hand?
I suspect the issue is that your primary key is a character column with a case insensitive collation (e.g. latin1_swedish_ci). If so, lower case and upper case letters are considered to be "equal", which would lead to a duplicate.
Here's a demonstration. Note the difference in the value of collation_name:
CREATE TABLE t3 (mycol VARCHAR(4) COLLATE latin1_swedish_ci PRIMARY KEY );
INSERT INTO t3 VALUES ('A'),('a');
-- Error Code: 1062
-- Duplicate entry 'a' for key 'PRIMARY'
CREATE TABLE t4 (mycol VARCHAR(4) COLLATE latin1_bin PRIMARY KEY );
INSERT INTO t4 VALUES ('A'),('a');
-- 2 row(s) affected
If you need MySQL to consider uppercase and lowercase letters to be unequal, then you need to specify either a case sensitive or a binary collation, rather than a case insensitive collation, for that column.
(NOTE: MySQL names collations that are case insensitive with a _ci on the end of the collation name, e.g. latin1_swedish_ci.)
If the column is currently latin1 characterset and latin1_swedish_ci collation, you probably want to change the collation on the column to be either latin1_general_cs or latin1_bin.
e.g.
ALTER TABLE t3 CHANGE mycol mycol VARCHAR(4) COLLATE latin1_general_cs ;
http://dev.mysql.com/doc/refman/5.5/en/case-sensitivity.html
http://dev.mysql.com/doc/refman/5.5/en/adding-collation.html
Not sure how you would get this error if you are correct that the PK and any other unique indexes are not being violated. A solution might be to use ON DUPLICATE KEY UPDATE or the IGNORE keyword.
Trying to make insert or update sql using the prepared statements from php's pdo. First I thought of using REPLACE INTO command,but it gives me an error because I have a foreign key on my index. Read that I must use INSERT...ON DUPLICATE KEY UPDATE syntax to make it working, but it's not clear for me how to do that with prepared statements. Any solution for this? Thanks.
The sql is :
$sql="REPLACE INTO fn_currencies(id,short,name,buy,sell,date) VALUES (:id,:short,:name,:buy,:sell,:update)";
UPD: I am making this query in Yii that uses personal wrapper over the PDO.
When I use unnamed parameters I get this type of error:
CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens. The SQL statement executed was: INSERT INTO `fn_currencies` (id,short,name,buy,sell,date) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE id=?,short=?,name=?,buy=?,sell=?,date=?
When I use the named parameters with differed names for Insert and Update as was mentioned..I get no errors and neither data is inserted in my DB.
Here is the schema for the DB:
CREATE TABLE IF NOT EXISTS `fn_currencies` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`short` varchar(4) NOT NULL,
`name` varchar(200) NOT NULL,
`buy` decimal(10,4) NOT NULL,
`sell` decimal(10,4) NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
ALTER TABLE `fn_currencies`
ADD CONSTRAINT `FK_fn_currencies` FOREIGN KEY (`id`) REFERENCES `fn_operations` (`currency_id`);
Thanks to DavaRandom, he pointed out an error in my code, but this should do the trick. Replace the named parameter with ? and use an array merge to make the SQL on the fly like this:
$sql="
insert INTO fn_currencies(id,short,name,buy,sell,date)
VALUES (?,?,?,?,?,?)
on duplicate key update currencies set
short=?, name=?, buy=?, sell=?, update=?";
$values=array("id"=>1, "short"=>36, "name"=>'Bazinga', "sell"=>3.67, "date"=>'2012-08-08');
$db->query($sql, array_merge(array_values($values),array_values($values)));
Apparently this will also work (See comments all over the page about yes/no/maybe) but the above will certainly work:
$sql="
insert INTO fn_currencies(id,short,name,buy,sell,date)
VALUES (:id,:short,:name,:buy,:sell,:update)
on duplicate key update currencies set
short=:short, name=:name, buy=:buy, sell=:Sell, update=:update";
I keep finding myself writing queries to avoid inserting when there are duplicates - things like
select * from foobar where bar=barbar and foo=foofoo
and then checking in PHP with mysql_num_rows() to see if the number of results is > 0 to determine whether to go forward with my insert.
EDIT: for instance, let's say a user wants to send an invitation to another user. I want to make sure that in my invitations table, I don't add another entry with the same pair invited_id AND game_id. so this requires some sort of check.
this feels inefficient (and slightly dirty). is there a better way?
What about unique index?
A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL.
http://dev.mysql.com/doc/refman/5.1/en/create-table.html
EDIT:
A column list of the form (col1,col2,...) creates a multiple-column index. Index values are formed by concatenating the values of the given columns.
http://dev.mysql.com/doc/refman/5.0/en/create-index.html
In this case, create a unique index on (bar, foo), so that the insert fails on duplicated value. You just need to handle the exception in php. This way, the code is cleaner and faster.
Just use a UNIQUE key on the columns and the INSERT IGNORE statement to insert new rows (duplicate rows are IGNORED).
Beware that the UNIQUE key may not exceed a 1000 bytes, meaning that the potential number of bytes contained in the fields foo and bar together may not exceed a 1000 bytes. If this creates a problem, just MD5 the CONCATENATED values into its own column at insert time, like (in PHP) md5($foo.$bar), and set the unique key to that column.
CREATE TABLE `test_unique` (
`id` int(10) unsigned NOT NULL auto_increment,
`foo` varchar(45) default NULL,
`bar` varchar(45) default NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `Unique` (`foo`,`bar`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT IGNORE INTO `test_unique` VALUES
(1, 'foo1', 'bar1'),
(2, 'foo2', 'bar2');
INSERT IGNORE INTO `test_unique` VALUES
(2, 'foo2', 'bar2');
I am creating a two MySQL tables in PHP, using the code as given below:
$sql = "CREATE TABLE qotwMember
(
MemberId NOT NULL PRIMARY KEY,
Name varchar(255),
Passwork varchar(255),
emailId varchar(255),
)";
$sql = "CREATE TABLE qotwQuestion1111
(
QuestionId NOT NULL AUTO_INCREMENT,
Question varchar(5000),
MemberId varchar(255) FOREIGN KEY fkname REFERENCES qotwMember(MemberId),
PostDate date,
Vote int,
PRIMARY KEY (QuestionId)
)";
mysql_query($sql,$con);
Then i try to insert data into these tables. In the qotwMember table, the data gets entered, but when I try to insert data into the qotwQuestion1111 table, it gives me the error "Error: Table 'database1.qotwQuestion1111' doesn't exist"
I can not figure out what I am doing wrong here. Please help me with this problem.
Note: Both the tables have been created in a different php.
Regards
Zeeshan
Are you sure you are selecting the right database each time? See: mysql_select_db()
I suspect you're not giving us the real SQL because neither of those statements will actually work - you're missing the datatype for the primary column and have some extra commas.
If that is your real SQL, then make sure you put or die(mysql_error($con)); after calls to mysql_query
When you are creating your tables, it is probably easier to use a MySQL front end such as MySQL query browser instead of trying to run the CREATE TABLE statements inside PHP. My guess is there is a syntax error in your second statement, so the table is not getting created. The front end will show you what the syntax error is.
Alternatively, you could check the return value of mysql_query to see if there is an error, and then use mysql_error() to read it out.
I have had the same problem as you with foreign key creation in MySQL (which is what your error is about).
When creating foreign keys, both the foreign key column and the reference column must be of the same data type and size. I noticed you did not give your primary key column any datatype or size. This is probably what is causing your error. Also, as others have pointed out, what engine you are using also will dictate if you can use foreign keys.
If you declare 'MemberID' as 'MemberID varchar(255) NOT NULL PRIMARY KEY' it should work as you have it now. I would suggest always giving your primary key columns a datatype and possible size. I don't know what your tables are for, but for a primary key column that is just an ID, i would recommend making it an INT of some sort (just remember to change your foreign key column to reflect that change).