Problem creating a reference table in mysql using php - 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).

Related

Is it possible to execute a multi-line SQL statment using PHP and Sqlite3 [duplicate]

I am trying to create a database using python to execute the SQL commands (for CS50x problem set 7).
I have created a table with an id field set to AUTO_INCREMENT, but the field in the database is populated only by NULL values. I just want it to have an incrementing id starting at 1.
I've tried searching online to see if I'm using the right syntax and can't find anything obvious, nor can I find someone else with a similar problem, so any help would be much appreciated.
Here is the SQL command I am running:
# For creating the table
db.execute("""
CREATE TABLE students (
id INTEGER AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
middle_name VARCHAR(255) DEFAULT (NULL),
last_name VARCHAR(255) NOT NULL,
house VARCHAR(10),
birth INTEGER
);
""")
# An example insert statement
db.execute("""
INSERT INTO students (
first_name,
middle_name,
last_name,
house,
birth
)
VALUES (
?, ?, ?, ?, ?
);
""", "Harry", "James", "Potter", "Gryffindor", 1980)
Here is a screenshot of the database schema shown in phpliteadmin :
And here is a screenshot of the resulting database:
My guess is that you are using SQLite with phpliteadmin and not MySql, in which case this:
id INTEGER AUTO_INCREMENT PRIMARY KEY
is not the correct definition of the auto increment primary key.
In fact, the data type of this column is set to INTEGER AUTO_INCREMENT, as you can see in phpliteadmin, which according to 3.1. Determination Of Column Affinity, has INTEGER affinity.
Nevertheless it is the PRIMARY KEY of the table but this allows NULL values.
The correct syntax to have an integer primary key is this:
id INTEGER PRIMARY KEY AUTOINCREMENT
This cannot happen, if your statements are executed correctly.
I notice that you are not checking for errors in your code. You should be doing that!
My guess is that the table is already created without the auto_increment attribute. The create table is generating an error and you are inserting into the older version.
You can fix this by dropping the table before you create it. You should also modify the code to check for errors.

Inserting into mysql table using foreign key with 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.

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.

How to ensure unique number sequentially in php using mysql?

I am developing an web application where I have to give every new registrant a serial number. The main issue is with 'how to ensure uniqueness?'. I have searched through the different functions available with mysql and found mysql_insert_id() to be the fittest solution here. But before I run towards it, I need to know whether this function is thread-free. To more precise, say there are two users sitting at two different terminals and submits the registration form synchronously. Will they both get the same id out of the execution of the function mysql_insert_id()? Otherwise, my project will spoil. Please help. If I could not clear my point, please comment. Thanks in advance.
here is detailed solution
CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)
By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.
To insert a new record into the "Persons" table, we will NOT have to specify a value for the "ID" column (a unique value will be added automatically):
If you have an id column on your table in your database and that column is set to be the primary key that will be enough. Even if 2 people will submit the form at the same the ids will be unique.
id column could be defined like this
ADD PRIMARY KEY (`id`)
id` int(11) NOT NULL AUTO_INCREMENT
Alternatively, you can use the UUID() function in mysql.
A UUID is designed as a number that is globally unique in space and
time. Two calls to UUID() are expected to generate two different
values, even if these calls are performed on two separate computers
that are not connected to each other.
mysql> SELECT UUID();
-> '6ccd780c-baba-1026-9564-0040f4311e29'
For further details : http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid

Problem creating a table using php

I am trying to create a table in MySql using php. My code looks like this:
$sql = "CREATE TABLE qotwQuestion1111
(
QuestionId int PRIMARY KEY AUTOINCREMENT,
Question varchar(5000),
MemberId varchar(255) FOREIGN KEY REFERENCES qotwMember(MemberId),
PostDate date,
Vote int
)";
mysql_query($sql,$con);
i am unable to create this table, the error is in the "AUTOINCREMENT" and also the "FOREIGN KEY" ..
Can someone tell me what am i doing wrong here. and what should i do to solve this problem please
Best
Zeeshan
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
The keyword is AUTO INCREMENT
http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
foreign keys are specified as constraints or by FOREIGN KEY fk_name REFERENCES table(key) .
When you have a problem with your sql syntax, it tells you to check your sql manual near where the error occurred. I suggest you take its advice.

Categories