CakePHP searching multiple models - php

I have a table called users and it is connected to coaches and clients.
I want to search in both users table and coaches table.
My tables look like this:
CREATE TABLE IF NOT EXISTS `team07`.`users` (
`id` INT(11) NOT NULL,
`email` VARCHAR(45) NOT NULL,
`password` VARCHAR(255) NOT NULL,
`usertype` CHAR(2) NOT NULL,
`created` DATETIME NOT NULL,
`modified` DATETIME NULL DEFAULT NULL,
`firstname` VARCHAR(45) NOT NULL,
`lastname` VARCHAR(45) NOT NULL,
`phonenumber` VARCHAR(45) NOT NULL,
`suburb` VARCHAR(45) NOT NULL,
`state` VARCHAR(10) NOT NULL,
`businessname` VARCHAR(45) NULL DEFAULT NULL,
`image` BLOB NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `email_UNIQUE` (`email` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
And also
CREATE TABLE IF NOT EXISTS `team07`.`coaches` (
`id` INT NOT NULL,
`coachid` INT NOT NULL,
`appstate` INT NOT NULL,
`bio` VARCHAR(2048) NULL,
`price` INT NULL,
PRIMARY KEY (`id`),
INDEX `COACH_INFOFK_idx` (`coachid` ASC),
UNIQUE INDEX `coachid_UNIQUE` (`coachid` ASC),
CONSTRAINT `COACH_INFOFK`
FOREIGN KEY (`coachid`)
REFERENCES `team07`.`users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
This is what the code I am doing looks like:
public function review()
{
//Select all users which are a Coach AND have appstate = 1 (Just signed up, in review)
$users = $this->paginate($this->Users);
$users = $this->Users->find('all')->where(['Users.usertype'=>'CO', 'Coaches.appstate'=>'1']);
$this->set(compact('users'));
$this->set('_serialize', ['users']);
}
However I am having issues because my page responds with
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'Coaches.appstate' in 'where clause'
How do I fix this?

If the association is understood by cake, you can use contain to load it:
https://book.cakephp.org/3.0/en/orm/query-builder.html#loading-associations
So something like this:
public function review()
{
//Select all users which are a Coach AND have appstate = 1 (Just signed up, in review)
$users = $this->paginate($this->Users);
$users = $this->Users->find('all')->contain(['Coaches'])->where(['Users.usertype'=>'CO', 'Coaches.appstate'=>'1']);
$this->set(compact('users'));
$this->set('_serialize', ['users']);
}

Related

Creating multiple models from one model in CakePHP

I have a users and a clients table.
They are linked as follows:
-- -----------------------------------------------------
-- Table `users`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`email` VARCHAR(45) NOT NULL,
`password` VARCHAR(255) NOT NULL,
`usertype` CHAR(2) NOT NULL,
`created` DATETIME NOT NULL,
`modified` DATETIME NULL DEFAULT NULL,
`firstname` VARCHAR(45) NOT NULL,
`lastname` VARCHAR(45) NOT NULL,
`phonenumber` VARCHAR(45) NOT NULL,
`suburb` VARCHAR(45) NOT NULL,
`state` VARCHAR(10) NOT NULL,
`businessname` VARCHAR(45) NULL DEFAULT NULL,
`image` BLOB NULL DEFAULT NULL,
`valid` INT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `email_UNIQUE` (`email` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `clients`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `clients` (
`id` INT NOT NULL AUTO_INCREMENT,
`user_id` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `CLIENTS_FK_idx` (`user_id` ASC),
CONSTRAINT `CLIENTS_FK`
FOREIGN KEY (`user_id`)
REFERENCES `users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
I have baked these two tables and I have created a users registration page. Upon form submission I want the database to create both a user and a client object.
Here is my UsersController method form CakePHP:
public function clientregistration()
{
//Register a new client. Client enters all details and the system sets usertype=CL
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->getData());
$user->usertype = 'CL';
$user->valid = 1;
if ($this->Users->save($user) && $this->Coaches->($coach)) {
$this->Flash->success(__('You have successfully registered.'));
return $this->redirect(['action' => 'login']);
}
$this->Flash->error(__('Registration failure. Please, try again.'));
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
I want the code to automatically pre-fill all data in the clients table as well.
How do I do this?
I do not know what you want to prefill, you have only user_id field to save. So if your associations are set correctly in UsersTable.php, you can save Client entity after you saved User:
$client = $this->Users->Clients->newEntity();
$client->user_id = $user->id;
$this->Users->Clients->save($client);

inserting php + mysql

Its my first time using php and mysql together. Here's my database's script:
CREATE SCHEMA IF NOT EXISTS `Alinfo_Express` ;
USE `Alinfo_Express` ;
CREATE TABLE IF NOT EXISTS `Alinfo_Express`.`Categorias` (
`idCategoria` INT(11) NOT NULL,
`titulo` VARCHAR(128) NOT NULL,
`descricao` TEXT NOT NULL,
PRIMARY KEY (`idCategoria`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
CREATE TABLE IF NOT EXISTS `Alinfo_Express`.`Produtos` (
`idProduto` INT(11) NOT NULL,
`nome` VARCHAR(256) NOT NULL,
`descricao` TEXT NOT NULL,
`precoUnidade` FLOAT NOT NULL,
`qtdEstocada` INT(11) NOT NULL,
`emDestaque` BIT(1) NOT NULL,
`idCategoria` INT(11) NOT NULL,
PRIMARY KEY (`idProduto`),
INDEX `fk_Produtos_Categorias1_idx` (`idCategoria` ASC),
CONSTRAINT `fk_Produtos_Categorias1`
FOREIGN KEY (`idCategoria`)
REFERENCES `Alinfo_Express`.`Categorias` (`idCategoria`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
CREATE TABLE IF NOT EXISTS `Alinfo_Express`.`Usuarios` (
`idUsuario` INT(11) NOT NULL,
`nome` VARCHAR(256) NOT NULL,
`sexo` CHAR(1) NOT NULL,
`cpf` VARCHAR(256) NOT NULL,
`rg` VARCHAR(256) NOT NULL,
`email` VARCHAR(256) NOT NULL,
`endereco` VARCHAR(256) NOT NULL,
`CEP` VARCHAR(256) NOT NULL,
`bairro` VARCHAR(256) NOT NULL,
`cidade` VARCHAR(256) NOT NULL,
`estado` VARCHAR(256) NOT NULL,
`senha` VARCHAR(256) NOT NULL,
`tipo` CHAR(1) NOT NULL,
PRIMARY KEY (`idUsuario`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
CREATE TABLE IF NOT EXISTS `Alinfo_Express`.`Compra` (
`idCompra` INT NOT NULL,
`valor` DECIMAL NOT NULL,
`tipoPagamento` VARCHAR(45) NOT NULL,
`dataCompra` DATETIME NOT NULL,
`idUsuario` INT(11) NOT NULL,
`idProduto` INT(11) NOT NULL,
PRIMARY KEY (`idCompra`),
INDEX `fk_Compra_Usuarios_idx` (`idUsuario` ASC),
INDEX `fk_Compra_Produtos1_idx` (`idProduto` ASC),
CONSTRAINT `fk_Compra_Usuarios`
FOREIGN KEY (`idUsuario`)
REFERENCES `Alinfo_Express`.`Usuarios` (`idUsuario`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Compra_Produtos1`
FOREIGN KEY (`idProduto`)
REFERENCES `Alinfo_Express`.`Produtos` (`idProduto`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Here's my code:
$MySQLi->query("INSERT INTO Produtos (idProduto, nome, descricao, precoUnidade,qtdEstocada, emDestaque, idCategoria) VALUES ($cod, '$nome', '$desc', $preco,$qtd, $dest, '$url', $cat);");
I don't know why it isn't working out. There's a long time I don't work with databases, that maybe be my problem.
You have couple of mistakes in your query. Try to execute in phpmyadmin. Try this one
$MySQLi->query("INSERT INTO Produtos (idProduto, nome, descricao, precoUnidade,qtdEstocada, emDestaque, idCategoria) VALUES ($cod, '$nome', '$desc', $preco, $qtd, $dest, '$url', $cat)");
It should work. In phpmyadmin, it will tell you error. Share it with us.
Here you can try with this i hope it will work
$MySQLi->query("INSERT INTO Produtos (idProduto, nome, descricao, precoUnidade,qtdEstocada, emDestaque, idCategoria) VALUES ('".$cod."', '".$nome."', '".$desc.'", '".$preco."','".$qtd."', '".$dest."', '".$url."', '".$cat."')");

Error fetching row from database with PHP

I am trying to fetch a row from a table in my database, and everything is retrieved successfully except for one column (page_content), whose data comes in partially. Here is the table creation code:
CREATE TABLE 'usol_site_page' (
'page_id' int(11) NOT NULL auto_increment,
'page_type_id' int(11) NOT NULL,
'page_menu_id' int(11) NOT NULL,
'page_name' varchar(100) NOT NULL,
'page_link' varchar(100) NOT NULL,
'page_heading' varchar(255) default '',
'page_content' text,
'page_title' varchar(255) default NULL,
'meta_keywords' mediumtext,
'keyword_description' text,
'pic_small' varchar(255) default NULL,
'pic_main' varchar(255) default NULL,
'pic_size' varchar(50) default NULL,
'pic_type' varchar(50) default NULL,
'display_order' int(11) NOT NULL,
'parent_page_id' int(11) NOT NULL,
'status' varchar(20) NOT NULL,
'creation_date' date NOT NULL,
'last_update_date' date NOT NULL,
PRIMARY KEY ('page_id'),
KEY 'Refusol_page_menu60' ('page_menu_id'),
KEY 'Refusol_page_type44' ('page_type_id'),
CONSTRAINT 'Refusol_page_menu60' FOREIGN KEY ('page_menu_id') REFERENCES 'usol_page_menu' ('page_menu_id') ON DELETE CASCADE,
CONSTRAINT 'Refusol_page_type44' FOREIGN KEY ('page_type_id') REFERENCES 'usol_page_type' ('page_type_id') ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=latin1
Does anyone know why page_content is not being fully retrieved?
here is the code the query :
$extendQry = "";
if($mode != "admin"){
$extendQry = "AND p.status='enable' ";
}
$qry = "SELECT p.page_id, p.page_link, p.page_name, p.page_heading, p.page_content, p.status, p.page_title,
p.meta_keywords, p.keyword_description, p.pic_main, p.pic_small, p.parent_page_id,
t.page_type_id, t.page_type, m.page_menu_id, m.menu_type
FROM usol_site_page p, usol_page_type t , usol_page_menu m
WHERE p.page_id = ".$pageId." $extendQry
AND t.page_type_id = p.page_type_id
AND m.page_menu_id = p.page_menu_id";
$result = mysql_query($qry);
return mysql_fetch_row($result);
fellas thank you very much for your quick responce sorry for my very unclear question, i got it solved by changing datatype of the column (page_content) from 'text' (64KB) to mediumtext(16MB). and it is working perfectly now. thank you all for your kind support you guyz are the best.

How to accurately set up a foreign key scenario in MySQL to accomplish my addressbook

I have been making a database and learning along the way. I recently got into using InnoDB and using foreign keys to connect tables together.
But in all honestly I'm probably making my foreign keys blindly. What is the correct set and check list that I need to use when making a foreign key.
My understanding with foreign keys is that I have a Master Table, and any changes in my Master Table are reflected to any tables that hold a foreign key to a specific column in it.
So my current log-in system has a set up like this
users
=====
id PK
username
password
and my other tables look like this
contacts
========
id PK
user_id references `users`.`id`
group
name
address
groups
======
id PK
user_id
group_name
group_contacts
==============
id PK
group_id references `group`.`id`
contact_id references `contacts`.`id`
To my understanding these tables can be deleted when the Master Table is deleted using the ON DELETE CASCADE option correct?
My problem now is that I can't seem to make group_id and contact_id a Foreign key to groups.id and contacts.id with this setup. I get an error when running the SQL statements.
I'm trying to make my address book so that when a user places a contact into a group becomes all automated and I don't have to change much information. The group_contact table is what I THINK I will querying when I want to see where each contact belongs to. If I change the name of a group it will reflect across all tables right? This is where foreign keys come in and I'm confusing myself with how these keys should behave for me.
But like I said I can't seem to make a foreign key without getting an error.
I know I can Google my Foreign Key question, which I have but I can't seem to learn this way without getting feedback and input to my exact scenario ;(
Not to ask too much but because of my confusion I'm also having a hard time trying to see how I can make a PHP script to handle the group name change and query the database to pull down contacts that belong to a specific group.
This would really help me a lot guys, and I hope to learn something!
My query is this:
ALTER TABLE `list_`.`groups_contacts`
ADD CONSTRAINT `group_id` FOREIGN KEY (`group_id`) REFERENCES `list_`.`groups` (`id`)
ADD CONSTRAINT `contact_id` FOREIGN KEY (`contact_id`) REFERENCES `list_`.`contacts` (`id`);
My database looks like this:
CREATE TABLE `list_`.`buyer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` tinyint(11) NOT NULL,
`isClosed` tinyint(1) NOT NULL,
`display_limit` int(1),
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`prop_address` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`state` varchar(11) NOT NULL,
`zip` varchar(5) NOT NULL,
`cell_phone` varchar(16) NOT NULL,
`home_phone` varchar(16) NOT NULL,
`other1` varchar(16) NOT NULL,
`other2` varchar(16) NOT NULL,
`comments` text NOT NULL,
`comment_exist` tinyint(1) NOT NULL,
`comment_date` text NOT NULL,
`date_added` date NOT NULL,
`date_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`,`user_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 AUTO_INCREMENT=23 ;
CREATE TABLE `list_`.`company` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` tinyint(11) NOT NULL DEFAULT '0',
`company_name` varchar(128) NOT NULL,
PRIMARY KEY (`id`, `user_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
CREATE TABLE `list_`.`contacts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` tinyint(11) NOT NULL,
`group` varchar(128) NOT NULL,
`first_name` varchar(128) NOT NULL,
`last_name` varchar(128) NOT NULL,
`address` varchar(128) NOT NULL,
`city` varchar(128) NOT NULL,
`state` varchar(2) NOT NULL,
`zip` int(5) NOT NULL,
`phone_number` varchar(16) NOT NULL,
`cell_number` varchar(16) NOT NULL,
`work_number` varchar(16) NOT NULL,
`fax_number` varchar(16) NOT NULL,
`email` varchar(128) NOT NULL,
`company` varchar(55) NOT NULL,
`title` varchar(56) NOT NULL,
`notes` text NOT NULL,
`date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`,`user_id`),
KEY `user_id` (`user_id`),
KEY `group` (`group`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 AUTO_INCREMENT=9 ;
CREATE TABLE `list_`.`groups` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` tinyint(11) NOT NULL,
`position` int(8) unsigned NOT NULL DEFAULT '0',
`name` varchar(128) NOT NULL,
`date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`,`user_id`),
KEY `user_id` (`user_id`),
KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8 AUTO_INCREMENT=32 ;
CREATE TABLE `list_`.`prospect` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` tinyint(11) NOT NULL,
`isClosed` tinyint(1) DEFAULT '0',
`display_limit` int(1) DEFAULT '0',
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`prop_address` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`state` varchar(11) NOT NULL,
`zip` varchar(5) NOT NULL,
`cell_phone` varchar(16) NOT NULL,
`home_phone` varchar(16) NOT NULL,
`other1` varchar(16) NOT NULL,
`other2` varchar(16) NOT NULL,
`comments` text NOT NULL,
`date_added` date NOT NULL,
`date_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`,`user_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
CREATE TABLE `list_`.`seller` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` tinyint(11) NOT NULL,
`file` int(11) DEFAULT NULL,
`isClosed` tinyint(1) NOT NULL,
`display_limit` int(1) NOT NULL DEFAULT '0',
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`prop_address` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`state` varchar(22) NOT NULL,
`zip` varchar(5) NOT NULL,
`cell_phone` varchar(16) NOT NULL,
`home_phone` varchar(16) NOT NULL,
`other1` varchar(16) NOT NULL,
`other2` varchar(16) NOT NULL,
`comments` text NOT NULL,
`comment_exist` tinyint(1) NOT NULL,
`comment_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`date_added` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`date_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`,`user_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8 AUTO_INCREMENT=21 ;
CREATE TABLE `list_`.`settings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` tinyint(11) NOT NULL,
`seller_display_limit` int(4) DEFAULT '0',
`buyer_display_limit` int(4) DEFAULT '0',
`prospect_display_limit` int(4) DEFAULT '0',
`property_display_limit` int(4) DEFAULT '0',
`date_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`,`user_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
CREATE TABLE `list_`.`users` (
`id` tinyint(11) NOT NULL AUTO_INCREMENT,
`md5_id` varchar(200) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`user_level` tinyint(1) DEFAULT '1',
`first_name` varchar(200) NOT NULL,
`last_name` varchar(200) NOT NULL,
`email` varchar(200) DEFAULT NULL,
`approved` int(1) NOT NULL,
`banned` int(1) NOT NULL,
`date_joined` date NOT NULL,
`ip` varchar(15) DEFAULT NULL,
`activation_code` int(9) DEFAULT NULL,
`ckey` varchar(220) NOT NULL,
`ctime` varchar(220) NOT NULL,
`last_logged_in` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`account_number` varchar(128) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
ALTER TABLE `list_`.`buyer`
ADD CONSTRAINT `buyer_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON UPDATE CASCADE;
--
-- Constraints for table `company`
--
ALTER TABLE `list_`.`company`
ADD CONSTRAINT `company_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON UPDATE CASCADE;
--
-- Constraints for table `contacts`
--
ALTER TABLE `list_`.`contacts`
ADD CONSTRAINT `contacts_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
ADD CONSTRAINT `group_ibfk_2` FOREIGN KEY (`group`) REFERENCES `groups` (`name`) ON UPDATE CASCADE;
--
-- Constraints for table `groups`
--
ALTER TABLE `list_`.`groups`
ADD CONSTRAINT `group_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
--
-- Constraints for table `prospect`
--
ALTER TABLE `list_`.`prospect`
ADD CONSTRAINT `prospect_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
--
-- Constraints for table `seller`
--
ALTER TABLE `list_`.`seller`
ADD CONSTRAINT `seller_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
--
-- Constraints for table `settings`
--
ALTER TABLE `list_`.`settings`
ADD CONSTRAINT `settings_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
I think you slightly misunderstood the concept of Foreign Keys. Changing the name of a group is not supposed to reflect on any other table, you just change your group-table.
Assuming you have this simple scenario, where one Contact can belong only to one Group:
Groups
id
group_name
Contacts
id
group_id -> Groups.id
first_name
...
Your Contacts do not have the information about the group_name. You just store the reference to your Groups.id.
If you want to query your contacts and the name of their group, you join those two tables:
Select c.first_name, g.group_name
From contacts c
Join groups g On ( g.id = c.group_id )
If you want to change the name of a group, you do a simple update:
Update groups
Set group_name = 'Your new group name'
Where id = 99 --# The id of the group to rename
This only changes your Groups table, without changing your Contacts.
Your Foreign Key on Contacts.group_id is there to ensure the referential integrity. This means, that you are not allowed to have a contact with group_id=88 if there is no record in Groups with id=88.
Using ON DELETE CASCADE would delete all Contacts that are members of a certain group, once you delete that group.

Unable to relate two MySQL tables (foreign keys)

Here is my USER table
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(100) NOT NULL,
`expiry` varchar(6) NOT NULL,
`contact_id` int(11) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(100) NOT NULL,
`level` int(3) NOT NULL,
`active` tinyint(4) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`,`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
And here is my contact_info table
CREATE TABLE IF NOT EXISTS `contact_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`email_address` varchar(255) NOT NULL,
`company_name` varchar(255) NOT NULL,
`license_number` varchar(255) NOT NULL,
`phone` varchar(30) NOT NULL,
`fax` varchar(30) NOT NULL,
`mobile` varchar(30) NOT NULL,
`category` varchar(100) NOT NULL,
`country` varchar(20) NOT NULL,
`state` varchar(20) NOT NULL,
`city` varchar(100) NOT NULL,
`postcode` varchar(50) NOT NULL,
PRIMARY KEY (`id`,`email_address`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
The system uses username to login users. I want to modify it in such a way that it uses email for login. But there is no email_address in users table.
I have added foreign key - email in user table(which is email_address in contact_info).
How should I query database?
No, no, no, no no. Seriously, no. Don't make me come over there :-)
You're breaking third normal form by storing the email address twice.
The relationship need only be a short one, that of id. Assuming you're not guaranteeing the IDs will be identical in the two tables (i.e., my users.id isn't necessarily equal to my contact_info.id), just add a ci_id to the users table to act as a foreign key to the contact_info table.
Then the query to get a user's username and email will be something like:
select u.username, ci.email
from users u, contact_info ci
where u.username = 'paxdiablo'
and u.ci_id = ci.id;

Categories