I have two simple table on Mysql Db with a foreign key constrain, let's say:
User (Userid,Name)
BorrowedBook (BookTitle, Userid)
I need to populate these table through a form, thus using Php.
What's the best practice to input consistent data on User and BorrowedBook?
I tried in several ways, including two separate INSERT INTO but I do have error message on Foreign Key constrain.
Related
How can I insert more than one row for the same value
for example, each user has to submit 2 forms so the username is the same in each form but the information is different
I tried to use UPDATE but it removes the ole information and replaces it with the new one while I want to keep both
is there a way to do that?
insert into your_table (username, col2)
values ('user1', 1),
('user1', 2)
Have two tables, 'USERS' and 'FORMSUBMISSIONS'
When a user submits a form for the first time, a new entry is created in the USERS table, which is unique for each user, and would contain information connected to the user.
And whenever a form is submitted (including the first time), an entry is written to the FORMSUBMISSIONS table with the details of that submission, and a foreign key back to USERS.
That's a cleaner data model for this situation. It will also help future queries on the data. If you are limited to a single table for some reason, then successive inserts will work as above, as long as there is no unique key on the USER field.
you can add duplicate data just your primary key can't be duplicated because it causes primary key constraint. so what you can do is have an extra column let's say "ID" make it your primary key. While submitting the row keep on adding ID column's value by one, rest of the data could be same.
It depends on whether your USERNAME column allows duplicates.
If it's the primary key of the table, your table schema doesn't support what you want to do, because PK should be UNIQUE.
If your USERNAME column allows duplicates, you can use INSERT:
declare #username varchar(max) = 'your_username' --declare a variable to use the same username
insert into table_name (username, form_data)
values(#username, 'form_data_1')
,(#username, 'form_data_2')
It also depends on how you're executing the SQL statement. I would definately go and create stored procedure to do this insert.
you can use bulk insert query for that. as suggested by #huergen but make sure that your username or any field that might be in form data does not have UNIQUE key index. you can also add another field that works like PRIMARY key in that table.so many ways to do but it depends upon your requirement.
Use below insert format to get your desired result:
insert into Table_name(Field1, Field2)
SELECT 'user_1', 1 UNION ALL
SELECT 'user_1', 2
How do you code in PHP to insert data into a table that has two foreign keys and these foreign keys are the primary key of different tables.
This is a many-to-many relationship so I am making a new table. I want to populate this table.
I searched a lot these past days on how to get the primary key of a row on the left table and right table to combine it in the middle table. But it all doesn't work. Please help.
You should use mysqli_insert_id() after each insert, keep each into its own variable, then use those as your FKs when inserting into the 3rd table.
It will return int. Have a look at the doc: PHP Doc
everyday i add almost 5000 new records in mysql and i want to prevent insert duplicate row in table,i think i should check all of the bank befor any insert operation,is it suitable?
Or there is any better way to do that??
thanks in advance
It's a good choice to prevent the data model beeing corrupted by software by applying a unique index to the field attributes which must not be duplicatable.
It's even better to ask the database for duplicate candidates before inserting data.
The best is, to have both combined. The security on the database model and the question for duplicates in the software layer because a) error handling is much more expensive than querying and b) the constraint protects the data from human failure.
mysql supports unique indexes with the CREATE UNIQUE INDEX statement.
e.g: CREATE UNIQUE INDEX IDX_FOO ON BAR(X,Y,Z);
creates a unique index on table BAR. This index will also be used when running the query for duplicates - speeds up the processing very much.
See MySQL Documentation for more details.
When you have a data integrity issue, you want the database to enforce the rules (if possible). In your case, you do this with a unique index or unique constraint, which are two names for the same thing. Here is sample syntax:
create unique index idx_table_col1_col2 on table(col1, col2)
You want to do this in the database, for three reasons:
You want the database to know that that column is unique.
You do not want a multi-threaded application to "accidentally" insert duplicate values.
You do not want to put such important checks into the application, where they might "accidentally" be removed.
MySQL then has very useful constructs to deal with duplicates, in particular, insert . . . on duplicate key update, insert ignore, and replace.
When you run SQL queries from your application, you should be checking for errors anyway, so catching duplicate key errors should be no additional burden on the application.
Firstly, any column that needs to be unique you can use the UNIQUE constraint:
CREATE TABLE IF NOT EXISTS tableName
(id SERIAL, someUniqueColumnName VARCHAR(255) NOT NULL UNIQUE);
See the MySQL Documentation for adding uniqueness to existing columns.
You need to decide what constitutes a duplicate in your table, because uniqueness is not always restricted to a single column. For instance, in a table where you store users with a corresponding id for something else, then it may be both combined which have to be unique. For that you can have PRIMARY KEY which uses two columns:
CREATE TABLE IF NOT EXISTS tableName (
id BIGINT(20) UNSIGNED NOT NULL,
pictureId BIGINT(20) UNSIGNED NOT NULL,
someOtherColumn VARCHAR(12),
PRIMARY KEY(id, pictureId));
Lately I have been doing some work with MySQL and have come across the need to store table names as a field in one of my tables (which is not ideal). Instead I would like to reference a list of tables that currently exist in the database as a foreign key. I have found that the information_schema database stores a list of these tables however I cannot reference them as a foreign key as they are Memory tables. Is there another way I can reference the list of tables in the database as a foreign key.
For those interested, the reason I need to store the table names is because I am developing a basic PHP framework that exposes each table in the database as a class.
How dynamic is the list of tables in your database? One option is to create your own table and (periodically) fill it with the table names from information_schema.
For example, I'm doing the next action:
SELECT COUNT(id)
FROM users
WHERE unique_name = 'Wiliam'
// if Wiliam don't exists then...
INSERT INTO users
SET unique_name = 'Wiliam'
The question is, I'm doing the SELECT COUNT(id) check every time I insert a new user, despite of using an unique key or not, so... if "unique_name" has an UNIQUE key it will be better for performance than using a normal key?
What you mean is a UNIQUE CONSTRAINT on the column which will be updated. Reads will be faster, Inserts will be just a bit slower. It will still be faster than your code checking first and then inserting the value though. Just let mysql do its thing and return an error to you if the value is not unique.
You didn't say what this is for, which would help. If its part of an authentication system, then why doesn't your query include the user's password as well? If it's not, a unique indexed column used to store names isn't going to work very well in a real-world system unless you are OK with having just 1 and only Wiliam in your system. (Was that supposed to be William?)
And if that name field is really unique you do not need to use COUNT(ID) in your query. If 'unique_name' is truly unique you either get an id number returned from your query or you get nothing.
You'd want something like this:
SELECT id FROM users WHERE unique_name = 'Wiliam'
No record return, no Wiliam.
An index (unique or non-unique -- I don't know what you're after here) on unique_name will improve the performance.
Your use of 'unique key' isn't very logical so I suspect you are getting confused about the nomenclature of keys, indexes, their relationships, and the purposes for them.
KEYS in a database are used to create and identify relationships between sets of data. This is what makes the 'relational' possible in a relational database.
Keys come in 2 flavors: Primary and foreign.
PRIMARY KEYS identify each row in a table. The value or values that comprise the key must be unique.
Primary keys can be made from a single column or made of several columns (in which case it is called a composite key) that together uniquely identifies the row. Again the important thing here is uniqueness.
I use MySql's auto-increment integer data type for my primary keys.
FOREIGN KEYS identify which rows in a table have a relationship with other rows in other tables. A foreign key of a record in one table is the primary key of the related record in the other table. A foreign key is not unique -- in many-to-many relationships there are by definition multiple records with the same foreign key. They should however be indexed.
INDEXES are used by the database as a sort of short-hand method to quickly look up values, as opposed to scanning the entire table or column for a match. Think of the index in the back of a book. Much easier to find something using a book's index than by flipping through the pages looking for it.
You may also want to index a non-key column for better performance when searching on that column. What column do you use frequently in a WHERE clause? Probably should index it then.
UNIQUE INDEX is an index where all the values in it must be distinct. A column with a unique index will not let you insert a duplicate value, because it would violate the unique constraint. Primary keys are unique indexes. But unique indexes do not have to be primary keys, or even a key.
Hope that helps.
[edited for brevity]
Having a unique constraint is a good thing because it prevents insertion of duplicated entries in case your program is buggy (are you missing a "for update" clause in your select statement?) or in case someone inserts data not using your application.
You should, however, not depend on it in your application for normal operation. Lets assume unique_name is an input field a user can specify. Your application should check whether the name is unique. If it is, insert it. If it was not, tell the user.
It is a bad idea to just try the insert in all cases and see if it was successful: It will create errors in the database server logs that makes it more difficult to find real errors. And it will render your current transaction useless, which may be an issue depending on the situation