How to avoid duplicate on insert of field values in mysql - php

Good day guys, I have a grade/score table in MySql that students record will be inserted into using php. I want to avoid a student having a score repeated for a term/period. What I mean is that a student cant have two(2) grades/scores for a subject(mathematics) in a term(periodOne) table. How do I accomplish this in MySql or php? here is how my table looks:
table periodOne (
id int AUTO_INCREMENT,
studentId int,
subjectId int,
score
)
Let me know if you need extra information. Thanks!!!!!!

you have to add a unique contraint in mysql like this : ALTER TABLE periodOne ADD CONSTRAINT uc_check UNIQUE(studentId, subjectId). You will also have to check with PHP that there is no existing row before to do your INSERT

You can declare the attribute as "Unique" by using UNIQUE CONSTRAINT for which you don't want duplicate value.
If your score are dependent on some other table also then you can use Composite Primary Key.

Related

Mysql duplicate row prevention [duplicate]

I want to add complex unique key to existing table. Key contains from 4 fields (user_id, game_id, date, time).
But table have non unique rows.
I understand that I can remove all duplicate dates and after that add complex key.
Maybe exist another solution without searching all duplicate data. (like add unique ignore etc).
UPD
I searched, how can remove duplicate mysql rows - i think it's good solution.
Remove duplicates using only a MySQL query?
You can do as yAnTar advised
ALTER TABLE TABLE_NAME ADD Id INT AUTO_INCREMENT PRIMARY KEY
OR
You can add a constraint
ALTER TABLE TABLE_NAME ADD CONSTRAINT constr_ID UNIQUE (user_id, game_id, date, time)
But I think to not lose your existing data, you can add an indentity column and then make a composite key.
The proper syntax would be - ALTER TABLE Table_Name ADD UNIQUE (column_name)
Example
ALTER TABLE 0_value_addition_setup ADD UNIQUE (`value_code`)
I had to solve a similar problem. I inherited a large source table from MS Access with nearly 15000 records that did not have a primary key, which I had to normalize and make CakePHP compatible. One convention of CakePHP is that every table has a the primary key, that it is first column and that it is called 'id'. The following simple statement did the trick for me under MySQL 5.5:
ALTER TABLE `database_name`.`table_name`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);
This added a new column 'id' of type integer in front of the existing data ("FIRST" keyword). The AUTO_INCREMENT keyword increments the ids starting with 1. Now every dataset has a unique numerical id. (Without the AUTO_INCREMENT statement all rows are populated with id = 0).
Set Multiple Unique key into table
ALTER TABLE table_name
ADD CONSTRAINT UC_table_name UNIQUE (field1,field2);
I am providing my solution with the assumption on your business logic. Basically in my design I will allow the table to store only one record for a user-game combination. So I will add a composite key to the table.
PRIMARY KEY (`user_id`,`game_id`)
Either create an auto-increment id or a UNIQUE id and add it to the natural key you are talking about with the 4 fields. this will make every row in the table unique...
For MySQL:
ALTER TABLE MyTable ADD MyId INT AUTO_INCREMENT PRIMARY KEY;
If yourColumnName has some values doesn't unique, and now you wanna add an unique index for it. Try this:
CREATE UNIQUE INDEX [IDX_Name] ON yourTableName (yourColumnName) WHERE [id]>1963 --1963 is max(id)-1
Now, try to insert some values are exists for test.

Insert Into on Duplicate Update creates me an unwanted row

I have a SQL query as follows-
"INSERT INTO users(id, rank) SELECT v.user, v.vote FROM votes v WHERE
v.assertion = '$ID' ON DUPLICATE KEY UPDATE
rank = ( CASE WHEN v.vote = '1' THEN rank+50 WHEN v.vote = '-1'
THEN rank-200 WHEN v.vote = '3' THEN rank+100 ELSE rank END)"
applied on a database with a table users with and id and rank field, and a votes table with a user and vote field. I have to update the rank of the users in the users table based on their vote.
I really like this kind of query, but I've noticed a problem: every time I execute this from my PHP script the query adds a row to the users table completely empty (with only an ID, which is A_I, and a rank of 1, when usually there would be other field as well). I can't really wrap my head around why this happens.
Any help/idea?
Your table does not have a primary key first provide a primary key to id
run this sql query
alter table user add primary key (id)
and than try it will work
There are two possible reasons :
The id column is not the primary key, and probably you table doesn't have a primary key at all.
Create a primary key like this :
alter table user add primary key (id)
If you insert an value of 0 in an auto increment column, a new id is generated. An auto incremented column must not contain the value 0.
There is also a more general problem with your approach : in fact you only insert the user id and the rank, other compulsory fields in the table (username) are missing. The insert part does not seem to be valid for this reason. If you use an insert on duplicate key update, you must make sure that the result is correct which ever of insert and update is executed.

insert data into a table - primary key constraint

I have a db table created like this
CREATE TABLE products(id INT,  
name varchar(32),  
PRIMARY KEY(id,name),  
quantity int,
avail varchar(5) );
If I use the following command on the command prompt, the value is inserted properly:
INSERT INTO products(name,quantity,avail) VALUES('stuffed bear doll',100,'OF_ST');
although the id is duplicated
but when I leave it inside the function like this
$query=sprintf("INSERT INTO products(name,quantity,avail) VALUES('%s',%d,'%s');",
$name,
$quan,
$avail);
mysql_query($query);
then there is no insertion done at all.
You needed to set auto_increment on the id field in your create table syntax. You can edit the column to add it.
Also, if $quan is not valid your SQL syntax will give you an error. Put quotes around it: VALUES('%s','%d','%s')
there is no problem in Your query but i think value of name field is duplicate. As your table structure id-name is primary mean two rows can not have same value of both id and name field. One time one field value can be same but not for both. And here in your table value of id field is always 0 so if in any row value of name field repeat it will not insert that row. And please make id as primary and auto increment so it will be better.
thanks

How to set a foreign key and retrieve or delete data from multiple tables?

I am new to php and mysql. I created a database named 'students' which contain two tables as 'student_details' which have fields like 'ID, Name, Age, Tel#, Address' and another table as 'fee_details' which have fields like 'ID(student_details table ID), Inst Id, Date, Receipt No'.
I want to set a foreign key and retrieve data from both tables when a student paid their fees and if a student passed out or discontinued I want a delete option to delete his all records from my tables. So please help me to solve this by PHP code and displays it in HTML while using a search form.
Enforcing referential integrity at the database level is the way to go. I believe when you said you wanted the delete "to delete his all records from my tables" you meant deleting the row and all its child records. You can do that by using foreign keys and ON DELETE CASCADE.
CREATE TABLE students
(
student_id INT NOT NULL,
name VARCHAR(30) NOT NULL,
PRIMARY KEY (student_id)
) ENGINE=INNODB;
CREATE TABLE fee_details
(
id INT,
date TIMESTAMP,
student_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id)
ON DELETE CASCADE
) ENGINE=INNODB;
With this, when a student is deleted from the students table, all its associated records will be deleted from fee_details.
you can try mysql_query() and mysql_assoc_array()

autoincrement as primary key causing duplicate entries

I want an id and name to be primary key for my table. I want to increment id with every insert, so i set it to auto_increment. The problem is when i insert into table a new entry with same name, it inserts it with a new id and there are duplicate entries with same name and different ids. I don't want to search the table beforehand to see if there is any entry beforehand. Please help me how to correct this problem.
I think you have done something like this
CREATE TABLE table1
id unsigned integer autoincrement,
name varchar,
....
primary key (id,name)
This primary key does not select on unique name, because the autoincrement id will always make the key as a whole unique, even with duplicate name-fields.
Also note that long primary keys are a bad idea, the longer your PK, the slower inserts and selects will execute. This is esspecially bad on InnoDB, because the PK is included in each and every secondary key, ballooning your index files.
Change it to this
CREATE TABLE table1
id unsigned integer autoincrement primary key,
name varchar,
....
unique index `name`(name)
If you want it to be unique by name, you need to add a unique index on the name field, and then you can use the mysql syntax for on duplicate key: mysql reference for on duplicate key
You could apply a unique index to your name field, or if you're storing people, allow duplicate names.
Add UNIQUE(your_column_name) where you should replace your_column_name with the column in your database.

Categories