I have a script which takes a database and generate export like query for the database as a backup. I need this script for a purpose. My php code is:
mysql_query("SHOW CREATE TABLE `myTable`");
there are 17 tables in the database. I am running a for loop for all 17 tables. I get the create table query with foreign key which I do not want. It returns like-
CREATE TABLE `customers` (
`person_id` int(10) NOT NULL,
`account_number` varchar(255) DEFAULT NULL,
`taxable` int(1) NOT NULL DEFAULT '1',
`deleted` int(1) NOT NULL DEFAULT '0',
UNIQUE KEY `account_number` (`account_number`),
KEY `person_id` (`person_id`),
CONSTRAINT `customers_ibfk_1` FOREIGN KEY (`person_id`) REFERENCES `people` (`person_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
because of the foreign key, it gets an error while running queries for creating tables. is there any way to get the sql without foreign key? like-
CREATE TABLE IF NOT EXISTS `customers` (
`person_id` int(10) NOT NULL,
`account_number` varchar(255) DEFAULT NULL,
`taxable` int(1) NOT NULL DEFAULT '1',
`deleted` int(1) NOT NULL DEFAULT '0',
UNIQUE KEY `account_number` (`account_number`),
KEY `person_id` (`person_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Disable foreign keys during the creation of your tables.
SET FOREIGN_KEY_CHECKS=0
CREATE TABLE a
CREATE TABLE b
...
Enable keys again
SET FOREIGN_KEY_CHECKS=1
You could disable foreign keys checks as suggested elsewhere. If you really want to remove the constraints from the CREATE TABLE statements the following code could be used, it assumes that $createSql will contain the CREATE TABLE SQL statement:
$createSql = preg_replace('/CONSTRAINT[^\n]+/im', '', $createSql);
$createSql = preg_replace('/,\s+\)/im', "\n)", $createSql);
Related
I have created tables in MYSQL as follows
Author Table
CREATE TABLE `author` (
`AuthorId` varchar(25) NOT NULL,
`AuthorName` varchar(50) NOT NULL,
PRIMARY KEY (`AuthorId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Books Table
CREATE TABLE `books` (
`DocId` int(11) NOT NULL,
`ISBN` varchar(13) NOT NULL,
PRIMARY KEY (`DocId`),
KEY `DocId` (`DocId`),
CONSTRAINT `books_ibfk_1` FOREIGN KEY (`DocId`) REFERENCES `document`
(`DocId`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Document Table
CREATE TABLE `document` (
`DocId` int(11) NOT NULL,
`Title` varchar(50) NOT NULL,
`PublishDate` date DEFAULT NULL,
`AuthorId` varchar(10) DEFAULT NULL,
`DocType` varchar(10) DEFAULT NULL,
PRIMARY KEY (`DocId`),
KEY `AuthorId` (`AuthorId`),
CONSTRAINT `document_ibfk_3` FOREIGN KEY (`AuthorId`) REFERENCES `author`
(`AuthorId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I made a server for my PHP website on XAMPP and am using mysql but when I try inserting the values in Document table I get
error while inserting the recordsCannot add or update a child row: a foreign
key constraint fails (`librarydb`.`document`, CONSTRAINT `document_ibfk_3`
FOREIGN KEY (`AuthorId`) REFERENCES `author` (`AuthorId`))
How do I resolve this issue?
Your linked fields author.AuthorId and document.AuthorId are not defined the same way.
From the docs:
Corresponding columns in the foreign key and the referenced key must
have similar data types. The size and sign of integer types must be
the same. The length of string types need not be the same.
So make them both varchar(10) NOT NULL - or whatever you need.
i'm trying to make an sql create table but I fail to make a foreign key.
My code :
Db::getInstance()->execute('
CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'sondage`(
`id` int(6) NOT NULL AUTO_INCREMENT,
`question` varchar(60) NOT NULL,
PRIMARY KEY(`id`)) ENGINE='._MYSQL_ENGINE_.' default CHARSET=utf8')
|| !Db::getInstance()->execute('
CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'sondage_reponse`(
`id` int(6) NOT NULL AUTO_INCREMENT,
`champ1` int(4) NOT NULL,
`champ2` int(4) NOT NULL,
`champ3` int(4) NOT NULL,
PRIMARY KEY(`id`)) ENGINE='._MYSQL_ENGINE_.' default CHARSET=utf8')
|| !Db::getInstance()->execute('
INSERT INTO '._DB_PREFIX_.'sondage_reponse (champ1,champ2,champ3)
VALUES (0,0,0)')
I want to make id from "sondage" foreign key in "sondage_reponse".I've tryed :
ALTER TABLE ps_sondage_reponse
ADD FOREIGN KEY fk_id_sdg(id)
REFERENCES sondage(id)')
But Prestashop can't add the foreign key.
Thx
i'd say to try this :
ALTER TABLE ps_sondage_reponse
ADD CONSTRAINT FK_id_sdg
FOREIGN KEY (id) REFERENCES sondage(id)
We have the following two tables:
CREATE TABLE IF NOT EXISTS `gp` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`amount` decimal(15,2) NOT NULL,
`user` varchar(100) NOT NULL DEFAULT '',
`status` tinyint(2) NOT NULL DEFAULT '1',
`ip` varchar(20) NOT NULL DEFAULT 'N/A',
`token` varchar(100) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS `gp_logs` (
`id` int(11) NOT NULL,
`log` varchar(1000) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
We JOIN them, for statistics, but we do this rarely, since the data from the 2nd table is not used too often except when we need to verify things.
Considering that we have many queries per second, how can our query be optimized to use 1 INSERT query instead of two and to insert the correct id in the 2nd table (gp_logs) that was generated by the INSERT into table gp?
Right now, we do a combination of MYSQL with PHP:
mysqli_query($con,"INSERT INTO `gp` (amount,user) VALUES ('1234','1')");
$id = mysqli_insert_id($con);
mysqli_query($con,"INSERT INTO gp_logs(id,log) VALUES ('$id','some_data')");
We want to eliminate the requirement of PHP for getting the last inserted ID and to insert both entries by running a single INSERT query (with a JOIN).
I have a table that I want to have an id that will auto increase itself but not be primary or unique.
Is this possible?
You should really create another table, in that case.
E.g.
CREATE TABLE `Calls` (
`Id` INT(10) AUTO_INCREMENT,
`From` VARCHAR(100) NOT NULL,
`To` VARCHAR(100) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=INNODB;
CREATE TABLE `CallHistory` (
`Id` INT(15) AUTO_INCREMENT,
`CallId` INT(10) NOT NULL,
`Text` VARCHAR(255) NOT NULL,
PRIMARY KEY (`Id`),
KEY `CallHistory_Calls_idx` (`CallId`),
CONSTRAINT `CallHistory_Calls`
FOREIGN KEY (`CallId`)
REFERENCES `calls` (`Id`)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=INNODB;
Here's a demo on SQLFiddle.
A benefit of this is that if you delete a row from Calls, the rows in CallHistory will also be deleted.
Running this query:
SELECT `Calls`.`Id`,
`Calls`.`From`,
`Calls`.`To`,
`CallHistory`.`Text`
FROM `Calls`, `CallHistory`
WHERE `Calls`.`Id` = `CallHistory`.`CallId`;
Gives results something like this:
This should work:
id int NOT NULL AUTO_INCREMENT
Anyway I don't see how it wouldn't stay unique unless you update existing values later
Yes, you need to set auto_increment constraint:
CREATE TABLE `test` (
`testID` int(11) NOT NULL, //primary key here
`testInc` int(11) NOT NULL AUTO_INCREMENT, //here is your non-primary auto increment column
PRIMARY KEY (`testID`),
KEY `testInc` (`testInc`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
and if you want this to be unique also then you may add unique constraint:
ALTER TABLE `test` ADD CONSTRAINT ux_unique_constraint UNIQUE `testInc`
I'm having a trouble with getting the id after inserting a new Record using PHP Doctrine Project.
In inserting a new record in a table with no parent table (no foreign key) no problem happens.
But when inserting a related record here comes the problem, that I get only the parent id which is useless in my case.
PHP code example:
$city = new City();
$city->name = "Baghdad";
$city->country_id = 6;
$city->save();
print_r($city->identifier());
exit;
The output is:
Array
(
[id] =>
[country_id] => 6
)
Why the ID is empty!, where the row was inserted successfully!.
I need this to do more insertion that based the city.id, like another areas that has this city as a parent.
Note using the $city->id causes this error:
Warning: Invalid argument supplied for foreach() in Doctrine/Record.php on line 1151
Database SQL Dump:
CREATE TABLE IF NOT EXISTS `country` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(64) collate utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=7 ;
CREATE TABLE IF NOT EXISTS `city` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(64) collate utf8_unicode_ci NOT NULL,
`country_id` int(11) NOT NULL,
PRIMARY KEY (`id`,`country_id`),
KEY `fk_city_country` (`country_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=11 ;
ALTER TABLE `city`
ADD CONSTRAINT `fk_city_country` FOREIGN KEY (`country_id`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
BTW: I'm using the Doctrine::generateModelsFromDb() method to generate ORM model classes.
PS: using the Doctrine version 1.2.1, mysql:innodb 5.0.75-0ubuntu10.2, and php 5.2.6-3ubuntu4.5.
A co-worker discovered the solution.
It was because of this line of code:
PRIMARY KEY (`id`,`country_id`),
I used this:
PRIMARY KEY (`id`),
And it works correctly.
It's a MySQL issue I guess. It's not, it's bug in my tables design.
Does print_r($city->get('id')); hold more information?