auto increment field gives error - php

How to make column autoincrement if other fields are alresdy defined in mysql?
Error
SQL query:
ALTER TABLE `registration` ADD `rid` INT NOT NULL AUTO_INCREMENT FIRST ,
ADD PRIMARY KEY ( `rid` )
MySQL said: Documentation
#1068 - Multiple primary key defined
Here is ddl
Field Type Collation Attributes Null Default Extra Action
rname varchar(255) latin1_swedish_ci No None Browse distinct values Change Drop Primary Unique Index Fulltext
rmobile varchar(255) latin1_swedish_ci No None Browse distinct values Change Drop Primary Unique Index Fulltext
first_name varchar(37) latin1_swedish_ci No None Browse distinct values Change Drop Primary Unique Index Fulltext
last_name varchar(27) latin1_swedish_ci No None Browse distinct values Change Drop Primary Unique Index Fulltext
date_of_birth varchar(45) latin1_swedish_ci No None Browse distinct values Change Drop Primary Unique Index Fulltext
address varchar(200) latin1_swedish_ci No None Browse distinct values Change Drop Primary Unique Index Fulltext
city varchar(150) latin1_swedish_ci No None Browse distinct values Change Drop Primary Unique Index Fulltext
state varchar(200) latin1_swedish_ci No None Browse distinct values Change Drop Primary Unique Index Fulltext
postal_code varchar(67) latin1_swedish_ci No None Browse distinct values Change Drop Primary Unique Index Fulltext
mobile_no varchar(18) latin1_swedish_ci No None Browse distinct values Change Drop Primary Unique Index Fulltext
email_id varchar(99) latin1_swedish_ci No None Browse distinct values Change Drop Primary Unique Index Fulltext
password varchar(25) latin1_swedish_ci No None Browse distinct values Change Drop Primary Unique Index Fulltext
payment bigint(50) No None Browse distinct values Change Drop Primary Unique Index Fulltext
pay tinyint(1) No None Browse distinct values Change Drop Primary Unique Index Fulltext
status tinyint(1) No None Browse distinct values Change Drop Primary Unique Index Fulltext
dt timestamp Yes NULL Browse distinct values Change Drop Primary Unique Index Fulltext

As the error states, you already have a primary key in the table and you cannot have two columns as a primary key in a table. So make you new column UNIQUE and not a PK:
ALTER TABLE `registration` ADD `rid` INT NOT NULL AUTO_INCREMENT UNIQUE

Related

Unique Employee ID in pHp [duplicate]

Is this possible in MySql ?? Can I have an auto-incrementing Primary Key, prefixed with a letter, something like R1234, R1235, R1236... ect ??
What you could do is store the key as two columns. A char prefix and an auto-incrementing int, both of which are grouped for the primary key.
CREATE TABLE myItems (
id INT NOT NULL AUTO_INCREMENT,
prefix CHAR(30) NOT NULL,
PRIMARY KEY (id, prefix),
...
No. But for MyIsam tables you can create a multi-column index and put auto_increment field on secondary column, so you will have pretty much the same you are asking:
CREATE TABLE t1 (prefix CHAR(1) NOT NULL, id INT UNSIGNED AUTO_INCREMENT NOT NULL,
..., PRIMARY KEY(prefix,id)) Engine = MyISAM;
INSERT INTO t1(prefix) VALUES ('a'),('a'),('b'),('b');
SELECT * FROM t1;
a 1
a 2
b 1
b 2
You can get more details from here
Note: it's not going to work for INNODB engine
you can do it with two fields like this. but you can't do it with one field to my knowledge.
create table foo (
code char,
id int unsigned not null auto_increment
primary key(id,code)
);

Disabling unique constraint on a column in a table MYSQL [duplicate]

ColumnName is Unique (UNIQUE KEY ColumnName).
I just want to make column not unique (must be very simple, but can not understand how).
If in phpMyAdmin check at column name and at bottom click on Unique icon, get #1062 - Duplicate entry '' for key 'RegistrationNumber'. OK, see it is because, clicking on icon it ADD UNIQUE.
There is Unique icon in Structure within row. But the icon is not click-able.
As in phpMyAdmin did not found how to do it, trying with query.
Based on advices tried ALTER TABLE TableName DROP INDEX ColumnName.
Get 1091 Can't DROP 'ColumnName'; check that column/key exists
Here https://stackoverflow.com/a/4414694/2465936 found This error means that you are trying to delete a key which is being used by another table. Possibly the ColumnName is used by another table.
Please advice what need to do to make column not unique.
With SHOW CREATE TABLE get
Array
(
[0] => Array
(
[Table] => 18_6_TransactionPartners
[Create Table] => CREATE TABLE `18_6_TransactionPartners` (
`Number` int(11) NOT NULL AUTO_INCREMENT,
`CompanyName` char(255) COLLATE utf8_unicode_ci NOT NULL,
`RegistrationNumber` char(255) COLLATE utf8_unicode_ci NOT NULL,
.......
PRIMARY KEY (`Number`),
UNIQUE KEY `Number_2` (`Number`),
UNIQUE KEY `CompanyName` (`CompanyName`,`RegistrationNumber`),
KEY `Number` (`Number`)
) ENGINE=InnoDB AUTO_INCREMENT=444 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
)
)
Update
Based on #Bart Friederichs advice tried ALTER TABLE 18_6_TransactionPartners DROP INDEX Number and changed column RegistrationNumber not not unique. Do not understand why (possibly had some mess with unique keys). In any case can change to not unique.
Probably you have a named INDEX. By using SHOW CREATE TABLE tbl you can find out the names of the indices. Then drop them by name (e.g. some test table):
mysql> SHOW CREATE TABLE test;
CREATE TABLE `test` (
`entry_id` int(11) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
UNIQUE KEY `k` (`entry_id`)
)
To drop the index, use this:
ALTER TABLE test DROP INDEX k;
Your key name is RegistrationNumber (as is told by the error message):
ALTER TABLE TableName DROP INDEX RegistrationNumber;
If your column was defined unique using UNIQUE clause, then you can do something like this:
ALTER TABLE mytable DROP INDEX constraint_name
For dropping the index do this:-
ALTER TABLE mytable DROP INDEX index_name;
You have to drop the index using the index name, not the column name.

MySQL fulltext search does not work

I have a MySQL table structured like this:
$sql = "CREATE TABLE test(
id INT NOT NULL,
title VARCHAR(512) NOT NULL COLLATE utf8_general_ci,
body TEXT NOT NULL COLLATE utf8_general_ci,
dateStored VARCHAR(32) NOT NULL COLLATE utf8_general_ci,
fileName VARCHAR(128) NOT NULL COLLATE utf8_general_ci,
FOREIGN KEY(id) REFERENCES `database`.`parent`(id)
);";
My storage engine is MYISAM.
Now, when I want to search in body field with the MATCH - AGAINST, there is no result…
This is my try:
$sql2 = "SELECT * FROM database.test
WHERE MATCH(body) AGAINST('?')";
$prepare = $pdo->prepare($sql2);
$prepare->execute( array( $pattern ) );
$fetch = $prepare->fetchAll();
It seems very basic but still my code do not work. Would you tell me what is wrong with my code?
Is this because of I have a field with references to another table?
Add more data. By default MySQL will ignore any word that is in 50% or more of the rows in the table as it considers it would be a 'noise' word.
With very few rows in a table, it is common to hit this 50% limit often (ie. if you have two rows, every word is in at least 50% of the rows!).
I think you are missing the FULLTEXT index on your field. You need to have a FULLTEXT index on a column to do MATCH AGAINST searches.
Either declare the FULLTEXT index with the table or alter your current table to include the index.
ALTER TABLE `test` ADD FULLTEXT (`body`)
Also, as some others have said, there is a cut off to the word length and there is also the 50% threshold that will prevent results from showing.
Try IN BOOLEAN MODE. This will not ignore any rows.
http://dev.mysql.com/doc/refman/5.6/en/fulltext-boolean.html
For MySQL versions 5.6+
You just need to add a FULLTEXT INDEX altering the table like Crackertastic described or define it directly in the CREATE TABLE statement.
Here is a working example:
-- DROP TABLE child;
-- DROP TABLE parent;
CREATE TABLE parent (
id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB; -- or MyISAM
CREATE TABLE child(
id INT NOT NULL,
title VARCHAR(512) NOT NULL COLLATE utf8_general_ci,
body TEXT NOT NULL COLLATE utf8_general_ci,
date_stored VARCHAR(32) NOT NULL COLLATE utf8_general_ci,
file_name VARCHAR(128) NOT NULL COLLATE utf8_general_ci,
parent_id INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (parent_id) REFERENCES parent(id),
FULLTEXT (body)
) ENGINE=InnoDB; -- or MyISAM
INSERT INTO child (id, title, body, date_stored, file_name, parent_id) VALUES('1','test title 1','test body 1','22.05.2014','file1.txt',5);
INSERT INTO child (id, title, body, date_stored, file_name, parent_id) VALUES('2','asd','qwer','31.07.2019','yxcv.txt',6);
INSERT INTO child (id, title, body, date_stored, file_name, parent_id) VALUES('3','gfdsa','trewq','21.04.2015','hjkl.txt',7);
SELECT
*
FROM
child
WHERE
MATCH(body) AGAINST('qwer')
;
The SELECT request returns the entry with the id = 2.
For older MySQL versions
In MySQL vesions older than 5.6 was not possible to define a FULLTEXT INDEX on an InnoDB table.
From the MySQL 5.5 docu:
Full-text indexes can be used only with MyISAM tables. (In MySQL 5.6 and up, they can also be used with InnoDB tables.)
So, one had to decide between using of FOREIGN KEY and FULLTEXT INDEX and choose the storage engine -- InnoDB or MyISAM. Since InnoDB supported FOREIGN KEY constraints, but didn't support FULLTEXT indexes.
An attempt to create a FULLTEXT INDEX on an InnoDB table
-- DROP TABLE child;
-- DROP TABLE parent;
CREATE TABLE parent (
id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB;
CREATE TABLE child(
id INT NOT NULL,
title VARCHAR(512) NOT NULL COLLATE utf8_general_ci,
body TEXT NOT NULL COLLATE utf8_general_ci,
date_stored VARCHAR(32) NOT NULL COLLATE utf8_general_ci,
file_name VARCHAR(128) NOT NULL COLLATE utf8_general_ci,
parent_id INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
) ENGINE=InnoDB;
ALTER TABLE `child` ADD FULLTEXT (`body`);
failed with an error:
Query: ALTER TABLE `child` ADD FULLTEXT (`body`)
Error Code: 1214
The used table type doesn't support FULLTEXT indexes
So, you had to use MyISAM for FULLTEXT INDEX. Then you just need to add a FULLTEXT INDEX altering the table like Crackertastic described or define it directly in the CREATE TABLE statement.
Here is a working example:
-- DROP TABLE child;
-- DROP TABLE parent;
CREATE TABLE parent (
id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM;
CREATE TABLE child(
id INT NOT NULL,
title VARCHAR(512) NOT NULL COLLATE utf8_general_ci,
body TEXT NOT NULL COLLATE utf8_general_ci,
date_stored VARCHAR(32) NOT NULL COLLATE utf8_general_ci,
file_name VARCHAR(128) NOT NULL COLLATE utf8_general_ci,
parent_id INT NOT NULL,
PRIMARY KEY (id),
FULLTEXT (body)
) ENGINE=MyISAM;
INSERT INTO child (id, title, body, date_stored, file_name, parent_id) VALUES('1','test title 1','test body 1','22.05.2014','file1.txt',5);
INSERT INTO child (id, title, body, date_stored, file_name, parent_id) VALUES('2','asd','qwer','31.07.2019','yxcv.txt',6);
INSERT INTO child (id, title, body, date_stored, file_name, parent_id) VALUES('3','gfdsa','trewq','21.04.2015','hjkl.txt',7);
SELECT
*
FROM
child
WHERE
MATCH(body) AGAINST('qwer')
;
The SELECT request returns the entry with the id = 2.

How to recreate id column? [duplicate]

I am trying to alter a table which has no primary key nor auto_increment column. I know how to add an primary key column but I was wondering if it's possible to insert data into the primary key column automatically (I already have 500 rows in DB and want to give them id but I don't want to do it manually). Any thoughts? Thanks a lot.
An ALTER TABLE statement adding the PRIMARY KEY column works correctly in my testing:
ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT;
On a temporary table created for testing purposes, the above statement created the AUTO_INCREMENT id column and inserted auto-increment values for each existing row in the table, starting with 1.
suppose you don't have column for auto increment like id, no, then you can add using following query:
ALTER TABLE table_name ADD id int NOT NULL AUTO_INCREMENT primary key FIRST
If you've column, then alter to auto increment using following query:
ALTER TABLE table_name MODIFY column_name datatype(length) AUTO_INCREMENT PRIMARY KEY
For those like myself getting a Multiple primary key defined error try:
ALTER TABLE `myTable` ADD COLUMN `id` INT AUTO_INCREMENT UNIQUE FIRST NOT NULL;
On MySQL v5.5.31 this set the id column as the primary key for me and populated each row with an incrementing value.
In order to make the existing primary key as auto_increment, you may use:
ALTER TABLE table_name MODIFY id INT AUTO_INCREMENT;
Yes, something like this would do it, it might not be the best though. You might wanna make a backup:
$get_query = mysql_query("SELECT `any_field` FROM `your_table`");
$auto_increment_id = 1;
while($row = mysql_fetch_assoc($get_query))
{
$update_query = mysql_query("UPDATE `your_table` SET `auto_increment_id`=$auto_increment_id WHERE `any_field` = '".$row['any_field']."'");
$auto_increment_id++;
}
Notice that the the any_field you select must be the same when updating.
The easiest and quickest I find is this
ALTER TABLE mydb.mytable
ADD COLUMN mycolumnname INT NOT NULL AUTO_INCREMENT AFTER updated,
ADD UNIQUE INDEX mycolumnname_UNIQUE (mycolumname ASC);
I was able to adapt these instructions take a table with an existing non-increment primary key, and add an incrementing primary key to the table and create a new composite primary key with both the old and new keys as a composite primary key using the following code:
DROP TABLE IF EXISTS SAKAI_USER_ID_MAP;
CREATE TABLE SAKAI_USER_ID_MAP (
USER_ID VARCHAR (99) NOT NULL,
EID VARCHAR (255) NOT NULL,
PRIMARY KEY (USER_ID)
);
INSERT INTO SAKAI_USER_ID_MAP VALUES ('admin', 'admin');
INSERT INTO SAKAI_USER_ID_MAP VALUES ('postmaster', 'postmaster');
ALTER TABLE SAKAI_USER_ID_MAP
DROP PRIMARY KEY,
ADD _USER_ID INT AUTO_INCREMENT NOT NULL FIRST,
ADD PRIMARY KEY ( _USER_ID, USER_ID );
When this is done, the _USER_ID field exists and has all number values for the primary key exactly as you would expect. With the "DROP TABLE" at the top, you can run this over and over to experiment with variations.
What I have not been able to get working is the situation where there are incoming FOREIGN KEYs that already point at the USER_ID field. I get this message when I try to do a more complex example with an incoming foreign key from another table.
#1025 - Error on rename of './zap/#sql-da07_6d' to './zap/SAKAI_USER_ID_MAP' (errno: 150)
I am guessing that I need to tear down all foreign keys before doing the ALTER table and then rebuild them afterwards. But for now I wanted to share this solution to a more challenging version of the original question in case others ran into this situation.
Export your table, then empty your table, then add field as unique INT, then change it to AUTO_INCREMENT, then import your table again that you exported previously.
You can add a new Primary Key column to an existing table, which can have sequence numbers, using command:
ALTER TABLE mydb.mytable ADD pk_columnName INT IDENTITY
I was facing the same problem so what I did I dropped the field for the primary key then I recreated it and made sure that it is auto incremental . That worked for me . I hope it helps others
ALTER TABLE tableName MODIFY tableNameID MEDIUMINT NOT NULL AUTO_INCREMENT;
Here tableName is name of your table,
tableName is your column name which is primary has to be modified
MEDIUMINT is a data type of your existing primary key
AUTO_INCREMENT you have to add just auto_increment after not null
It will make that primary key auto_increment......
Hope this is helpful:)
Well, you have multiple ways to do this:
-if you don't have any data on your table, just drop it and create it again.
Dropping the existing field and creating it again like this
ALTER TABLE test DROP PRIMARY KEY, DROP test_id, ADD test_id int AUTO_INCREMENT NOT NULL FIRST, ADD PRIMARY KEY (test_id);
Or just modify it
ALTER TABLE test MODIFY test_id INT AUTO_INCREMENT NOT NULL, ADD PRIMARY KEY (test_id);
How to write PHP to ALTER the already existing field (name, in this example) to make it a primary key? W/o, of course, adding any additional 'id' fields to the table..
This a table currently created - Number of Records found: 4 name VARCHAR(20) YES
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
This an end result sought (TABLE DESCRIPTION) -
Number of records found: 4
name VARCHAR(20) NO PRI
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
Instead of getting this -
Number of Records found: 5
id int(11) NO PRI
name VARCHAR(20) YES
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
after trying..
$query = "ALTER TABLE racehorses ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id)";
how to get this? -
Number of records found: 4
name VARCHAR(20) NO PRI
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
i.e. INSERT/ADD.. etc. the primary key INTO the first field record (w/o adding an additional 'id' field, as stated earlier.
No existing primary key
ALTER TABLE `db`.`table`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);
;
Table already has an existing primary key'd column
(it will not delete the old primary key column)
ALTER TABLE `db`.`table`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
CHANGE COLUMN `prev_column` `prev_column` VARCHAR(2000) NULL ,
DROP PRIMARY KEY,
ADD PRIMARY KEY (`id`);
;
Note: column must be first for auto increment which is why the FIRST command.

PHP MySQL Error creating table: Cannot add foreign key constraint

I am trying to write a PHP script to create 2 tables in the same database, which should be linked through a 1 (table category) to many (table page) relationship. Hence, primary key 'category_id' from the 'category' table should be the foreign key in the table 'page'.
The table 'category' creates successfully without problems:
$sql="CREATE TABLE category(
category_id SMALLINT NOT NULL AUTO_INCREMENT,
category VARCHAR(30) NOT NULL,
PRIMARY KEY (category_id),
UNIQUE (category)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
Then I am trying to create the second table 'page':
$sql="CREATE TABLE page(
page_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
category_id SMALLINT UNSIGNED NOT NULL,
title VARCHAR(100) NOT NULL,
description TINYTEXT NOT NULL,
content LONGTEXT NOT NULL,
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (page_id),
FOREIGN KEY (category_id) REFERENCES category (category_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
And I get the following error:
Error creating table: Cannot add foreign key constraint
Could you please tell me what's wrong with my code? Thanks a lot in advance.
Per the MySql manual at http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html:
Corresponding columns in the foreign key and the referenced key must have similar data types.
The size and sign of integer types must be the same.
The problem is that you're specifying your foreign key as UNSIGNED, while your primary is not. Make sure that your foreign key matches the specifications of its parent.
From the MySQL Using FOREIGN KEY Constraints documentation:
Corresponding columns in the foreign key and the referenced key must have similar data types. The size and sign of integer types must be the same.
In your page table, the category_id is SMALLINT UNSIGNED, but in category it's just SMALLINT. They need to be exactly the same.
The columns used for your foreign key must have a matching specification. Here you have one category_id column signed, while the other is unsigned. Change one.
you problem is the UNSIGNED in category_id.
try to remove it
try
$sql="CREATE TABLE page(
page_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
category_id SMALLINT NOT NULL,
title VARCHAR(100) NOT NULL,
description TINYTEXT NOT NULL,
content LONGTEXT NOT NULL,
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (page_id),
FOREIGN KEY (page.category_id) REFERENCES category (category.category_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";

Categories