mysql - insert id from parent table - php

I have table definitions:
create table users(
id int not null auto_increment,
usernaname varchar(50) not null,
pass varchar(50) not null,
primary key(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
create table users_description(
user_id int not null,
description varchar(255),
key(user_id),
foreign key(user_id) references users(id) on delete cascade
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and it is good, works nice.
but when I add a new user I use a next query:
insert into users (username, pass) values('test', 'test');
but how to add a id of user automatically in users_description table?
Something similar to to this:
insert into users_description values(
select id from users where username = 'test',
'user description');
I want to use only two queries, is this possible?

You can use LAST_INSERT_ID() to get the last inserted primary key id (which would be from the users table):
INSERT INTO users_description VALUES
(LAST_INSERT_ID(), 'test', 'user description');

$query = mysql_query("insert form (username, pass) values('test', 'test')");
$id = mysql_insert_id();
gives you the last inserted id in PHP ..

Use LAST_INSERT_ID(). Example here.

Related

Query consult doctrine composite key

Hello I am try to take data with dictrine 2.5 from a table but I do not know how to do it.
SQL FILE
DROP DATABASE composite_key;
CREATE DATABASE composite_key;
USE composite_key;
CREATE TABLE company (
id_company INT NOT NULL AUTO_INCREMENT,
name VARCHAR(200) NULL,
PRIMARY KEY (id_company)
);
CREATE TABLE users (
id_user INT NOT NULL AUTO_INCREMENT,
name VARCHAR(200) null,
PRIMARY KEY (id_user)
);
CREATE TABLE reference (
id_company INT NOT NULL,
id_user INT NOT NULL,
createat TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id_company),
FOREIGN KEY (id_company) REFERENCES company(id_company),
FOREIGN KEY (id_user) REFERENCES users(id_user)
);
INSERT INTO users (`name`) VALUES ('test1');
INSERT INTO users (`name`) VALUES ('test2');
INSERT INTO users (`name`) VALUES ('test3');
INSERT INTO company (`name`) VALUES ('company1');
INSERT INTO company (`name`) VALUES ('company2');
INSERT INTO company (`name`) VALUES ('company3');
INSERT INTO reference (`id_company`,`id_user`) VALUES (1,1);
INSERT INTO reference (`id_company`,`id_user`) VALUES (2,2);
INSERT INTO reference (`id_company`,`id_user`) VALUES (3,3);
QUERY WHICH I HAVE TRIED
$dql = "SELECT r FROM CompositeBundle:Reference r JOIN CompositeBundle:Company c JOIN CompositeBundle:Users u WHERE c.idCompany = 1 AND u.idUser = 1 ";
$dql = "SELECT r FROM CompositeBundle:Reference r JOIN r.idUser JOIN r.idCompany WHERE r.idCompany = 1 AND r.idUser = 1 ";
If somone know to do these dql please sat It.

FOREIGN KEY ..again

I have read and searched all the site, but nothing I had found worked for me...so please help a newbie understand what he is doing wrong.
So I am trying to create an add to favorite function.
I need to create 3 tables. The first two worked like magic, but the 3rd one ...well I got in the trouble with the FOREIGN KEY
I get no error message, but it won't create the 3rd table.
Here are my codes:
<?php
$connect = mysql_connect("127.0.0.1","root","");
$db = mysql_select_db("mydb");
mysql_query("CREATE TABLE IF NOT EXISTS users
(
userid bigint,
firstname varchar(25),
lastname varchar(15),
email varchar(250),
gender varchar(10),
username varchar(15),
password varchar(15),
age int,
activ boolean,
date TIMESTAMP NULL default CURRENT_TIMESTAMP
)ENGINE=INNODB
");
mysql_query("CREATE TABLE IF NOT EXISTS products (
productid int(11) NOT NULL AUTO_INCREMENT,
productname varchar(100) NOT NULL,
productdescription varchar(250) NOT NULL,
price decimal(6,2) NOT NULL,
PRIMARY KEY (`productid`)
) ENGINE=INNODB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ");
mysql_query("CREATE TABLE IF NOT EXISTS favorites
(
userid bigint NOT NULL,
productid int(11) NOT NULL,
PRIMARY KEY (userid, productid),
FOREIGN KEY (userid) REFERENCES user (userid) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (productid) REFERENCES product (productid) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=INNODB
");
echo "The DataBase was successfully created!";
mysql_close();
?>
The foreign keys refer to non-existing tables.
The tables are names users and products while the third table refers to them as user and product (singular).
"userid" of "user" table must be primary key.

Can't insert : A foreign key constraint fails

I have the following tables:
CREATE TABLE IF NOT EXISTS `location`(
`ID` int(11) NOT NULL,
`name` varchar(25) NOT NULL,
`water` varchar(25) NOT NULL,
`fodder` varchar(25) NOT NULL,
`access` varchar(25) NOT NULL,
PRIMARY KEY (`ID`)
KEY `water` (`water`)
KEY `fodder` (`fodder`)
KEY `access` (`access`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
CREATE TABLE IF NOT EXISTS `watercondition`(
`ID` int(11) NOT NULL,
`watervalue` varchar(25) NOT NULL,
PRIMARY KEY (`watervalue`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
CREATE TABLE IF NOT EXISTS `foddercondition`(
`ID` int(11) NOT NULL,
`foddervalue` varchar(25) NOT NULL,
PRIMARY KEY (`foddervalue`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
CREATE TABLE IF NOT EXISTS `accesscondition`(
`ID` int(11) NOT NULL,
`accessvalue` varchar(25) NOT NULL,
PRIMARY KEY (`accessvalue`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
And for constraints table :
ALTER TABLE `location`
ADD CONSTRAINT `location_ibfk2` FOREIGN KEY (`water`) REFERENCES `watercondition` (`watervalue`),
ADD CONSTRAINT `location_ibfk3` FOREIGN KEY (`fodder`) REFERENCES `foddercondition` (`foddervalue`),
ADD CONSTRAINT `location_ibfk4` FOREIGN KEY (`access`) REFERENCES `accesscondition` (`accessvalue`);
In my php file, i want to insert a value to all of the table like this :
$sqlwater = "INSERT INTO `watercondition` (`ID`, `watervalue`) VALUES ('".$_SESSION['loc_id']."', '$watervalue')";
$resultwater = mysqli_query($con, $sqlwater) or die (mysqli_error($con));
$sqlfodder = "INSERT INTO `foddercondition` (`ID`, `foddervalue`) VALUES ('".$_SESSION['loc_id']."', '$foddervalue')";
$resultfodder = mysqli_query($con, $sqlfodder) or die (mysqli_error($con));
$sqlaccess = "INSERT INTO `accesscondition` (`ID`, `accessvalue`) VALUES ('".$_SESSION['loc_id']."', '$accessvalue')";
$resultaccess = mysqli_query($con, $access) or die (mysqli_error($con));
$sqlloc = "INSERT INTO `location` (`ID`, `name`) VALUES ('".$_SESSION['loc_id']."', '$name')";
$resultaccess = mysqli_query($con, $access) or die (mysqli_error($con));
But when I execute the php file, I get this error :
Cannot add or update a child row: a foreign key constraint fails (mydb.location, CONSTRAINT location_ibfk2 FOREIGN KEY (water) REFERENCES watercondition (watervalue))
When I check on my db, the value from water, fodder, and access have already been inserted db, but not in my location table.
The insert into the location table must also include values for the water, fodder and location columns. They are columns in the location table and cannot just be ignored.
Also you were using the wrong query variable in the final query.
I guess what is happening here is that the constraints are being validated by MYSQL before it checks that you have values for all the NOT NULL fields, so you get the constraint error before the more obvious one about missing column values.
$sqlloc = "INSERT INTO `location`
(`ID`, `name`, `water`, `fodder`, `location`)
VALUES ('{$_SESSION['loc_id']}', '$name',
'$watervalue', '$foddervalue', '$accessvalue' )";
$resultaccess = mysqli_query($con, $sqlloc) or die (mysqli_error($con));
You should insert foreign key to your location table to maintain relation you have created before.
Your query for location should be like
`$sqlloc = "INSERT INTO 'location' ('ID', 'name', 'water', 'footer', 'access') VALUES ('".$_SESSION['loc_id']."', '$name', 'water-related-id', 'fodder-related-id, 'access-related-id)";`
Anyway, primary key for a table should be 'id' column and foreign key should be other table's primary key, so your constraints should be
ALTER TABLE 'location'
ADD CONSTRAINT 'location_ibfk2' FOREIGN KEY ('water') REFERENCES 'watercondition' ('id'),
ADD CONSTRAINT 'location_ibfk3' FOREIGN KEY ('fodder') REFERENCES 'foddercondition' ('id'),
ADD CONSTRAINT 'location_ibfk4' FOREIGN KEY ('access') REFERENCES 'accesscondition' ('id');
And, your foreign key data type should match referenced table's key which in your case is int(11).
Are you doing this for college assignment?
Change your last insert statement like below:
"INSERT INTO `location` (`ID`, `name`,`water`,`fodder`,`access`) VALUES
('".$_SESSION['loc_id']."', '$name','$watervalue','$foddervalue','$accessvalue')";
Explanation:
ERD:
Look the yellow marked tables are the parent tables and your location table is child table.
So according to MySQL you cannot add or update a child table row (location) by some foreign key values which don't exist in corresponding parent table(s).
In your first three insert statements you are updating your three parent tables which is fine.
But in your final insert statement you are trying to update your child table where you provide with no values for those foreign keys which is an exception.
SQL FIDDLE
Reference
Twothings to note here:
First of all, your insert is not working because you made all the foreign keys "NOT NULL" fields, so when you insert a record on the location table you must provide those values.
Second, you must make sure the fields that are foreign keys has the same data type on the original table. In your code you are using INT(11) id fields on the original tables but are using VARCHAR(25) on the location table and you are linking to the field holding the value instead of linking to the primary key (id) field of the referenced table.
Kind regards,
Daniel

Symfony2 MySQL: INSERT SELECT syntax error

I am having problems with writing correct MySql query. I want to insert new collection for every user with id higher than 1000 but less than 10000.
$conn = $this->em->getConnection();
$stmt = $conn->prepare('INSERT INTO collection (name, type)
values(:name, :type)
SELECT * FROM user WHERE id<:endUser AND id>:startUser');
$stmt->bindValue('name', 'Default');
$stmt->bindValue('type', 0);
$stmt->bindValue('startUser', 1000);
$stmt->bindValue('endUser', 10000);
$stmt->execute();
This what I tried to write, but I get syntax error. Please explain me how to correct query
UPD
I should have given detailed structure of tables.
Collection
CREATE TABLE IF NOT EXISTS `collection` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`type` smallint(6) NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_FC4D6532A76ED395` (`user_id`)
);
User
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
);
User has one-to-many relationship with Collection.
With a SELECT INTO you have to select the values you want to place in the new row and only those values. And you dont use the VALUES() clause.
As you are using static values for the new rows and not values from the user table you can do it like this.
Oh and I see in your edit you were using the wrong table name It should have been fos_user
Also as fos_user.user_id is a NOT NULL field you need to include that column in the list of fields in the insert.
$conn = $this->em->getConnection();
$stmt = $conn->prepare('INSERT INTO collection (user_id, name, type)
SELECT id, 'default', 0
FROM fos_user
WHERE id > :startUser AND id < :endUser');
$stmt->bindValue('startUser', 1000);
$stmt->bindValue('endUser', 10000);
$stmt->execute();

How to insert new field in mysql database

Let assume we've database table My_table with (id-name)
CREATE TABLE `drink` (
`id` int(5) NOT NULL auto_increment,
`name` varchar(64) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=9034 ;
INSERT INTO `My_table` VALUES (1, 'my name is someone');
How to automate adding new fields using php or something else so that it can be (id-new-name)
and where new = name after we replace spaces to - using
$new = str_replace(' ', '-', trim($name));
so the table become
CREATE TABLE `drink` (
`id` int(5) NOT NULL auto_increment,
`new` varchar(64) NOT NULL default '',
`name` varchar(64) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=9034 ;
INSERT INTO `My_table` VALUES (1, 'my-name-is-someone', 'my name is someone');
I'd like to operate it cause it has half million of lines and impossible to do it manually
so any idea!
Thanks for help.
You might want to do that:
Adding a new column to the table:
ALTER TABLE drink ADD new varchar(100) after id;
Setting values for the new column using the pattern you described:
UPDATE drink SET new = REPLACE(name, ' ', '-');
RESOURCES:
http://dev.mysql.com/doc/refman/5.5/en/alter-table.html
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
When you insert anything i MySQL you have to specify the columns..Like this
INSERT INTObanans(id,sort) VALUES ('1','Green')
If you only need the value back, and don't need to search by new, you can:
SELECT id, REPLACE(name, ' ','-') AS new, name
FROM drink
Similar to what Macovei suggested, you can generate the new name when you insert a new record by doing this:
INSERT INTO drink (new, name) VALUES ('the name', REPLACE('the name', ' ', '-'))

Categories