(php)import .sql and add columns if table exists or create new table

909 Views Asked by At

I don't know if its possible.

I released a script version 1.0 and now I am about to release 1.2 version and I made some upgrade in database tables like change name field size or default value also added few new columns and table then export full db to .sql file(new db).

Is it possible from PHP to import new .sql file and add new tables and also change columns structure without deleting any data from table and add new columns in existing tables?

I tried to import it but it shows this error:

ALTER TABLE table1 ADD PRIMARY KEY (id);: Multiple primary key defined

Example:

Old Database v1.0

Table 1

  • ID (primary key , AI)
  • First Name(size-50 ,default - none)
  • Last Name(size-50 ,default - none)
  • Email(size-50 ,default - none)
  • Password(size-50 ,default - none)

New Database v1.2

Table 1

  • ID (primary key , AI)
  • First Name(size-100 ,default - none)
  • Last Name(size-100 ,default - none)
  • Email(size-255 ,default - none)
  • Password(size-50 ,default - none)
  • Gender (size 10 , default - none)

Added Table 2

  • ID (primary key , AI)
  • coloum1 (size-100 ,default - none)
  • coloum2 (size-255 ,default - none)

Is it possible to import new .sql over old database without loosing any data from PHP and also add data from new database?

I done my best to explain and hope you understand.

EDIT: I use this code to import new .sql file and its not working: How do I import a .sql file in mysql database using PHP?

1

There are 1 best solutions below

0
Red Acid On

you get that message because column id already exist and has KEY, if its PRIMARY KEY and AUTOINCREMENTED then it can not be duplicated, try this:

ALTER TABLE Table1 ADD COLUMN Gender varchar(10) NOT NULL DEFAULT 'none';
ALTER TABLE Table2 ADD COLUMN coloum1 varchar(100) NOT NULL DEFAULT 'none';
ALTER TABLE Table2 ADD COLUMN coloum2 varchar(255) NOT NULL DEFAULT 'none';

or just import the new columns