Inserting into mysql table using foreign key with PHP - php

Hi I have two tables,
users_table and orders table.
users_id is in both tables
as a primary key in users_table and as foreign key in orders_table(referencing users_id in users_table)
When I try to place an order if it's the first time the user is able to place an order but if a user already placed an order the data is not saved to the database in the second attempt.. any Idea why? or any solutions?
I apologise for the bad english
MY PHP CODE:
$query = "INSERT INTO orders_table(users_id, orders_postDate, orders_category, orders_categoryId, orders_name, orders_description, orders_deliveryDate) VALUES('$users_id', '$orders_postDate', '$orders_category', '$orders_categoryId', '$orders_name', '$orders_description', '$orders_deliveryDate')";
$result = mysqli_query($connection, $query);
if($result){
echo "SUCCESS";
}else{
echo "fail";
}
so Let's say that I created an account, signed in and placed an order, the data is successfully on the database. if I try to place a new order with the same user I get the fail message.. so for some reason
mysqli_query($connection, $query);
fails the second time, I am assuming that it is because my foreign key is a primary key? how can I fix this?

Without code/error message it is difficult to say what the issue is. However, you mentioned that user_id is the foreign key for the orders_table, but if it is also used for the primary key for your orders_table it would cause duplication when creating any subsequent orders, hence, insertion of a new order would fail.
These might help you to help us to get a better understanding of whats going on.
How is your orders_table created?
What is the primary key for Orders_table?
How do you assign the primary key (if you do) upon insertion of a new record?
Since you are able to insert the first record that means you get a successful connection. So instead of echoing "success" and "fail", extract the mysqli error instead.
Also, since you are dealing with MySQL and PHP you might want to take a look into using PDO objects instead, if you haven't already. Being able to use prepared statements is a huge plus.

Yes, you are right, if orders_table.user_id with primary key, also there is a 'unique' key. If so, MySql did not allow to paste the same user_id.
Use ALTER TABLE sql command to remove the primary key on orders_table.user_id add add a new column with primary key.
There is code you need:
ALTER TABLE orders_table DROP PRIMARY KEY;
ALTER TABLE orders_table ADD COLUMN `id` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE orders_table ADD PRIMARY KEY(`id`);

Your insert query is not getting data from the users_table and so will not be able to insert the right user data into the Orders_table; and second, the order_table is created having user_id as a primary key and foreign key which will cause data duplication. Try altering the table to drop the primary and create another column for it(Primary key).
An example
ALTER TABLE orders_table DROP PRIMARY KEY;
ALTER TABLE orders_table ADD COLUMN 'id' int NOT NULL AUTO_INCREMENT PRIMARY KEY;
That should make your code work now.

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.

How to limit number of entries in MySQL database?

how to limit the number of entry in inserting data in mysql database using php to 1
Any suggestions? Thanks .
You probably can't get it right in PHP since the trip back and forth to the database leaves room for another part of your application to create an entry. Normally we achieve this sort of thing by putting a unique index on the table that prevents duplication of data. For example:
CREATE TABLE alf_mimetype
(
id BIGINT NOT NULL AUTO_INCREMENT,
version BIGINT NOT NULL,
mimetype_str VARCHAR(100) NOT NULL,
PRIMARY KEY (id),
UNIQUE (mimetype_str)
) ENGINE=InnoDB;
If you attempt to insert a row with duplicate mimetype_str, the database will generate an exception. Catch it in your application and you'll know that your single entry for that particular row is already there.
You can create UNIQUE keys on multiple columns as well. Your primary key also represents a unique constraint and can consist of multiple columns.

Why can't I insert the same ID into the 'id' column of my MySQL table?

I'm creating a messaging system and I'm trying to set it up so it will have a "conversation view" and so users can reply to a message. To do this I have to have a primary ID for each conversation in the table and then a separate unique ID for each message.
My problem is that when I try replying to a message I get this error:
Duplicate entry '98' for key 1
It looks like it isn't allowing me to use the same ID in a column, but I don't have a 'unique' thing set in the table AFAIK.
I also tried to drop the PRIMARY for the id column but got this error:
The message is:
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
I don't understand why it won't let me insert the same ID into the id column, because as you know I need an ID for each conversation.
The mysql_query that I'm using to insert the reply into the table is:
$sql = "INSERT INTO messages (id, message_id, to_user, message, subject, from_user, date, time, date_short)
VALUES ('$id', '$message_id', '$to', '$message', '$subject', '$user', '$date', '$time', '$date_short')";
mysql_query($sql) or die(mysql_error());
Thanks in advance!
Your primary key can not be repeated, otherwise it isn't so useful as a key, is it? The primary key must uniquely identify the record.
The reason you're getting the error is that the column is set to be auto-number. You have not added that column to a separate key, which is a requirement for auto-number columns in MySQL.
Add it to a key/index with that column first, then remove the PK attribute. Make sure you have some PK in the table.
You can't have auto_increment without a key
I suspect you have AUTO_INCREMENT setup on your id field. If this is the case, then the values in the id column must be unique.
Either remove the AUTO_INCREMENT attribute on that column (by redefining the column without AUTO_INCREMENT via an ALTER TABLE command), or don't specify the id value in your INSERT statement.
First, untick AUTO_INCREMENT option on your column and as the second step, try to drop the index again
PRIMARY KEYs are also unique. auto_increment columns must be primary keys. You can't drop PRIMARY KEY from a column without making it not auto_increment.
However, I don't think you should change your table like this. You should keep your IDs and either create a new table with the data you need to update, or use UPDATE instead of INSERT.
Columns with primary keys can't have duplicates, otherwise they lose their uniqueness. MySQL will prevent same values. Having to alter primary key vales is also bad news. You may want to re-approach what you're doing and possibly create more tables.

Doctrine PHP Question

I was wondering if you can specify the order in which table definitions and data fixtures are loaded using the CLI. My problem is that I have two tables, each having a foreign key constraint pointing to the other, so one of the constraints needs to be added after a record has been added. Or maybe there's a better way of doing this...I'm no db expert and my head is fuzzy today.
Schema:
CREATE TABLE clients (
id INT AUTO_INCREMENT,
name VARCHAR(255), address VARCHAR(255),
primary_contact_user_id INT # References a user record in the users table
...
);
CREATE TABLE users (
id INT AUTO_INCREMENT,
username VARCHAR(255),
client_id INT # References a client record in the clients table
...
);
ALTER TABLE clients
ADD CONSTRAINT clients_primary_contact_user_id_users_id
FOREIGN KEY (primary_contact_user_id) REFERENCES users(id);
ALTER TABLE users
ADD CONSTRAINT users_client_id_clients_id
FOREIGN KEY (client_id) REFERENCES clients(id);
I'm also not a DB expert, but I do spend a lot of time working with them. I believe the circular reference is actually incorrect.
Regardless of whether DB theory sanctions it or not, you could get one field though a join to another table, so it is an unnecessary circular reference. I'd suggest that you eliminate one and alter any queries to reflect this change.
Based on a guess, I'd suggest that you eliminate primary_contact_user_id, as that almost sounds like a possible many-to-many relationship where a single item is elected as "primary"...
If you feel this design is necessary, can you please explain why?
put the INSERT statements between the CREATE TABLE and ALTER TABLE statements.

Problem creating a reference table in mysql using php

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).

Categories