database - Is there anyway i can Insert Records in Multiple Tables using single MySQL Query? -


i have user form users fill in following details

a) username b) password c) email

username , password belongs users table whereas email belongs contacts table , users table have foreign key contact_id stores primary key id of contacts. whenever user submit form have make 2 mysql queries insert records 2 different table.

here using.

first query:

$sth = $this->dbh->prepare("insert contacts(email) values(:email)"); 

second query :

$sth = $this->dbh->prepare("insert users(username,password,registerdate,activationstring,contact_id) values(:username,:password,now(),:activationstring,".$this->dbh->lastinsertid().")"); 

is there anyway make query 1 instead of two? utilizing mysql last_insert_id() function. ?

thank you

insert statement allows insert 1 table.

but create stored procedure job.

example:

create table contacts(   id int(11) not null auto_increment,   email varchar(255) default null,   primary key (id) );  create table users(   id int(11) not null auto_increment,   username varchar(255) default null,   `password` varchar(255) default null,   registerdate date default null,   activationstring varchar(255) default null,   contact_id varchar(255) default null,   primary key (id) );  delimiter $$  create procedure add_new_user(in p_username         varchar(255),                        in p_password         varchar(255),                        in p_registerdate     date,                        in p_activationstring varchar(255),                        in p_email            varchar(255)                        ) begin   insert contacts (email) values (p_email);   insert users (username, password, registerdate, activationstring, contact_id) values (p_username, p_password, p_registerdate, p_activationstring, last_insert_id ()); end $$  delimiter ;  set @p_username = 'user1'; set @p_password = 'pwd'; set @p_registerdate = now(); set @p_activationstring = 'str'; set @p_email = 'addr@host.net'; call database3.add_new_user(@p_username, @p_password, @p_registerdate, @p_activationstring, @p_email); 

stored procedure optional, can use 2 insert statements.


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -