I have 2 tables:
Warehouse (Parent)
Subwarehouse (Child)
Here is the creation of tables
//Create Warehouse Table
function einv_createWarehouseTable($conn, $db_type){
// Create SQL Statement To Create Table according to Database
$sql = "
CREATE TABLE IF NOT EXISTS `einv_warehouse` (
`einv_wh_id` INT(11) NOT NULL AUTO_INCREMENT,
`einv_wh_code` VARCHAR(4) NOT NULL,
`einv_wh_name` VARCHAR(255) NOT NULL,
`einv_wh_desc` TEXT NOT NULL,
`einv_wh_remark` TEXT NULL,
PRIMARY KEY (`einv_wh_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
";
//Create Sub Warehouse Table
function einv_createSubWarehouseTable($conn, $db_type){
// Create SQL Statement To Create Table according to Database
$sql = "
CREATE TABLE IF NOT EXISTS `einv_subwarehouse` (
`einv_whs_id` INT(11) NOT NULL AUTO_INCREMENT,
`einv_whs_wh_id` INT(11) NOT NULL,
`einv_whs_code` VARCHAR(4) NOT NULL,
`einv_whs_name` VARCHAR(255) NOT NULL,
`einv_whs_desc` TEXT NOT NULL,
`einv_whs_remark` TEXT NULL,
PRIMARY KEY (`einv_whs_id`),
FOREIGN KEY (`einv_whs_wh_id`) REFERENCES einv_warehouse(`einv_wh_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
";
I would like to be able to delete my parent table alongside clearing the entire child data.
I'd prefer an alternative method besides using on delete cascade which will result me into altering the table.
It is troublesome because these codings would require a drop and install process which is time consuming since there are many existing tables.
tl;dr - another method to delete all child data when selected parent id is
deleted
besides using on delete cascade
Here is my delete sql in my function.php page:
base_executeSQL("DELETE FROM einv_warehouse WHERE einv_wh_id = " . $whid . "");
base_executeSQL("DELETE FROM einv_subwarehouse WHERE einv_whs_id = " . $whid . "");
Related
I have seen my question may already have an answer, and "in mysql, on delete cascade not working" seems to be more similar..... but I can't see anything advised on that post working for me.
The problem is, when I delete a recipe, I want that its attachment gets also deleted (well, step by step, at the moment I am just trying to remove it from mysql table, not from the folder where it is stored).
After I post here a similar question but regarding how to create mysql trigger, I set the foreign key, and on delete cascade, so I though, when a recipe gets delete, the attachment as well, but it happens absolutely nothing to the attachment.... What am I doing wrong?
Next to each recipe I have a button to delete it:
echo '<a class="toLink" href="delete_recipe.php?id=' . $recipe['id'] . '" title="delete recipe" onclick="return confirm(\'Are you sure you want to delete this recipe?\');">Delete recipe</a>';
In delete_recipe.php:
<?php require 'includes/functions.php';
$recipeId = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
if(delete_recipe($recipeId) == true) {
header('Location: index.php');
exit;
} else {
$error_message = "Could not delete recipe";
}
In functions.php:
function delete_recipe($recipe_id = ':recipe_id') {
include 'db_connection.php';
try {
$sql = "DELETE FROM recipes ";
$sql .= "WHERE id =:recipe_id ";
$sql .= "LIMIT 1";
$results = $conn->prepare($sql);
$results->bindParam(':recipe_id', $recipe_id, PDO::PARAM_INT);
if($results->execute()) {
echo '1 row has been removed';
}
$conn = null;
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage() . '<br />';
return false;
}
return true;
}
I think I have set the foreign key and "delete on cascade" properly..... if I do:
show create table recipes:
| recipes | CREATE TABLE `recipes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`attachment_id` int(11) NOT NULL,
`chef_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_recipes_attachments1_idx` (`attachment_id`),
KEY `fk_recipes_chefs1_idx` (`chef_id`),
CONSTRAINT `fk_recipes_attachments1` FOREIGN KEY (`attachment_id`) REFERENCES `attachments` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_recipes_chefs1` FOREIGN KEY (`chef_id`) REFERENCES `chefs` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 |
show create table attachments:
| attachments | CREATE TABLE `attachments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`attachment_path` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 |
Any idea why it does not remove the attachment from the attachments table that belongs to the recipe I am deleting?
Thank you
You have your foreign key relationship backwards. The attachments table should have a recipe_id column, and that should be a foreign key to recipes.
CREATE TABLE `attachments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`attachment_path` varchar(255) NOT NULL,
`recipe_id` INT(11),
PRIMARY KEY (`id`),
FOREIGN KEY (`recipe_id`) REFERENCES `recipe` (`id`) ON DELETE CASCADE
);
The way you did it, deleting an attachment would delete the recipe.
I have an adjacency table with parent and child elements and when I delete my parent element I would like to delete all his child.
My table:
id name parent
1 Name1 null
2 SubName1 1
When I'm trying to delete row with id=1 I would like to delete and id=2
How can I do this?
My table:
CREATE TABLE IF NOT EXISTS `cats` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`parent` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `parent` (`parent`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Foreign keys could be the solution.
How you create them is dependent on your used Database.
At foreign keys there is a primary key defined which is like a "parent", if the parent gets deleted the childs get deleted to if you define it.
I've googled my question and read through a bunch of forum posts but I've yet to find the answer I'm looking for hopefully someone here can help me out.
For a project I'm building I've set up the following 3 tables; users, projects and projectUsers.
I've set up a form where I can add users to projects by saving the userID and the projectID in the projectUsers table nothing special so far. The form contains a select element with userIDs that can be connected to a projectID (hidden field).
This form element is filled with a query set up with Zend_Db_Select it selects all the users from the users table and adds it to the select. However I want to filter that result so it excludes all of the users already added to that specific project.
Short version: I have a select element with users filled with a resultset from a (Zend_db_select) database query I want that resultset to be stripped from certain userIDs.
For extra reference the table scheme below:
CREATE TABLE IF NOT EXISTS `projects` (
`projectID` int(11) NOT NULL AUTO_INCREMENT,
`projectName` varchar(255) NOT NULL
PRIMARY KEY (`projectID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `projectUsers` (
`projectUserID` int(11) NOT NULL AUTO_INCREMENT,
`projectID` int(11) NOT NULL,
`userID` int(11) NOT NULL
PRIMARY KEY (`projectUserID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `users` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
`userFirstName` varchar(255) DEFAULT NULL,
`userLastName` varchar(255) DEFAULT NULL
PRIMARY KEY (`userID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Thanks in advance!
addint to Soica Micea ans
$blackList = array(1,3,5,6); //user id which you want to exclude
$db->select()->from('users', '*')
->joinLeft('projectUsers', 'projectUsers.projectUserID = users.userID', null)
->where('projectUsers.projectID = ?', someProjectID)
->where('projectUserID is null')
->where('users.userID not in (?)', implode(',',$blackList))
->query()->fetchAll();
This will select all users that have not been added to a project and ignore users from arrayOfUserIds
select()->from('users', '*')
->joinLeft('projectUsers', 'projectUsers.projectUserID = users.userID', null)
->where('projectUsers.projectID = ?', someProjectID)
->where('projectUserID is null')
->where('users.userID not in (?)', arrayOfUserIds)
->query()->fetchAll();
I'm new to MySQL and PHP so Im not sure how to approach this problem I'm having.
I have two tables right now.
CREATE TABLE `users` (
`userid` int(25) NOT NULL AUTO_INCREMENT,
`username` varchar(65) NOT NULL DEFAULT '',
`password` varchar(32) NOT NULL DEFAULT '',
`emailaddress` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`userid`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
and
CREATE TABLE `images` (
`userid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`image` blob,
PRIMARY KEY (`userid`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
so what I want to do is when a user signs in I want to be able to display an image that the user uploaded.
do I have to do something to the tables to make theme reference from each other?
help please!
Do you want just?...
select image from images
left join users on users.userid=images.userid
where username='whateverusername';
in the second table , the attribute userid should be a foreign key (i'd rather use Innodb to make sure that there is a foreign key constraint but it's up to u to use innodb or not)
so your table should look like this
CREATE TABLE images ( userid int(10) unsigned NOT NULL, name
varchar(50) DEFAULT NULL, image blob, foreign key userid
references users(userid) on delete cascade ) ENGINE=InnoDB
AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
once you do that, the table images will be linked to the table users which means that no record will be added to the table images unless the user id is already in the table users
if you wanna grab all the informations about that users including the image , you can perform a join between the two tables.
example with php
$con = mysql_connect("localhost","mysql_user","mysql_pwd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$user_id = 1;
$results = array();
> $results =mysql_query("select t1.userid,t1.username,t2.name,t2.image from users as t1 left join images as t2 on t1.userid=t2.userid where userid = $user_id",$con);
UPDATE:
make sure that the type of userid in both tables match
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?