I have a little problem to insert data in 2 tables and need some help with it.
For example:
Table 1:
CREATE TABLE tb1 (
tb1_id int(5) not null AUTO_INCREMENT PRIMARY KEY,
tb1_title varchar(50),
tb1_cat varchar(50)
);
Table 2:
CREATE TABLE tb2 (
tb2_id int(5) not null AUTO_INCREMENT PRIMARY KEY,
tb2_title varchar(50),
tb2_doc varchar(200),
id_tb1 int(5) not null REFERENCES tb1(tb1_id)
);
One entry of tb1 can have many information(rows) of tb2, but how to insert the id of tb1 in some rows of tb2?
formular.php:
$sqla = "INSERT INTO tb_1 (tb1_title, tb1_cat) VALUES ('$tb1_title', '$tb1_cat')";
$sqlb = "INSERT INTO tb_2 (tb2_title, tb2_doc, <b>[? ? ?]</b>) VALUES ('$tb2_title', '$tb2_doc', <b>[? ? ?]</b>)";
mysqli_query($db, $sqla);
mysqli_query($db, $sqlb);
What do I have to change here?
You can get the value of tb1_id using mysqli_insert_id(), and then insert that into tb2:
$sqla = "INSERT INTO tb1 (tb1_title, tb1_cat) VALUES ('$tb1_title', '$tb1_cat')";
if (mysqli_query($db, $sqla)) {
$tb1_id = mysqli_insert_id($db);
$sqlb = "INSERT INTO tb2 (tb2_title, tb2_doc, id_tb1) VALUES ('$tb2_title', '$tb2_doc', $tb1_id)";
mysqli_query($db, $sqlb);
}
Yes you can.. try this..
BEGIN;
INSERT INTO tb_1 (tb1_title, tb1_cat) VALUES ('$tb1_title', '$tb1_cat');
INSERT INTO tb_2 (tb2_title, tb2_doc, <b>[? ? ?]</b>,id_tb1) VALUES ('$tb2_title', '$tb2_doc', <b>[? ? ?]</b>,LAST_INSERT_ID());
COMMIT;
$sqla = "INSERT INTO tableA (col1, col2) VALUES (val1, val2)";
mysqli_query($db,$sqla);
$id = mysqli_insert_id($db); //add it here.
$sqlb = "INSERT INTO tableB (col1,col2) VALUES (val1, val2, ...)";
//then you can pass the id into your second query
//...
Related
Morning, budies. I have an API call to bring me the profilesIds registereds in my websystem. I wanna make delete from my sqlserver table what is not content in my request response.
I do a select with the properties to show me what i have in common with my slqserver table and my response, and i do a delete with remaining.
In theory, it was supposed to work but no.
Have any mistake in sintax plz?
I currently have have 391 registers in my sql server table and only 389 is comum with my sqlserver table and response call.
When i do a select, bring me only that registers in common, idk wasnt working.
Select Query (bring me only 389 registers that i mentioned, is right).
foreach ($result as $indUser => $userInfos){
$agentId = $userInfos['id'];
$dhInsert = date("Y-m-d H:i:s");
foreach ($userInfos['profileIds'] as $indProfile => $idProfile){
$sql = "SELECT agentId, profileId
FROM LIVEPERSON_USERPROFILES
WHERE agentId = :agentId
AND profileId = :idProfile";
$stmt = Conexao::getConnection()->prepare($sql);
$stmt->bindValue(":agentId",$agentId,PDO::PARAM_STR);
$stmt->bindValue(":idProfile",$idProfile,PDO::PARAM_STR);
$rows = $stmt->execute();
}
}
Delete Query not working.
foreach ($result as $indUser => $userInfos){
$agentId = $userInfos['id'];
$dhInsert = date("Y-m-d H:i:s");
foreach ($userInfos['profileIds'] as $indProfile => $idProfile){
$sql = "DELETE FROM LIVEPERSON_USERPROFILES
WHERE NOT EXISTS (SELECT agentId, profileId
FROM LIVEPERSON_USERPROFILES
WHERE agentId = :agentId
AND profileId = :idProfile)";
$stmt = Conexao::getConnection()->prepare($sql);
$stmt->bindValue(":agentId",$agentId,PDO::PARAM_STR);
$stmt->bindValue(":idProfile",$idProfile,PDO::PARAM_STR);
$rows = $stmt->execute();
}
}
Data of table:
insert into testTable (agentId, profileId) values ('1536989','12345')
insert into testTable (agentId, profileId) values ('1536989','56789')
insert into testTable (agentId, profileId) values ('1536989','99999')
insert into testTable (agentId, profileId) values ('1536874','56789')
insert into testTable (agentId, profileId) values ('1536874','56984')
insert into testTable (agentId, profileId) values ('7568594','99999')
insert into testTable (agentId, profileId) values ('8895874','56984')
insert into testTable (agentId, profileId) values ('8895874','56789')
insert into testTable (agentId, profileId) values ('8895874','77777')
insert into testTable (agentId, profileId) values ('8895874','99999')
insert into testTable (agentId, profileId) values ('1235689','56789')
insert into testTable (agentId, profileId) values ('1235689','77777')
insert into testTable (agentId, profileId) values ('1245365','56984')
insert into testTable (agentId, profileId) values ('1245365','56789')
insert into testTable (agentId, profileId) values ('1245365','77777')
insert into testTable (agentId, profileId) values ('1245365','99999')
Obs: One agentId can have multiples profileIds, so, agentId is duplicated.
In data of table, i show that agentId 1536989 have a profile: 12345, 56789 and 99999. But in request, this agent have only 12345, 56789 profile. So i need delete from table the skill 9999 (f that happens it is successfull).
You don't need the subquery.
$sql = "DELETE FROM LIVEPERSON_USERPROFILES
WHERE agentId = :agentId AND profileId <> :idProfile)";
How i solved:
First, in foreach that i use to open the loop of response, i made a array to save this values and transform in querystring:
foreach ($result as $indUser => $userInfos){
$agentId = $userInfos['id'];
$dhInsert = date("Y-m-d H:i:s");
$forDelete[] = array(
'agentIdForDelete' => "'".$agentId."'",
'profileIdForDelete' => "'".implode("','",$userInfos['profileIds'])."'",
);
After, i print $forDelete and get this response:
Responsejson
Then i set a loop to iterate index and execute my delete query:
for ($i = 0; $i < count($forDelete); $i++){
$agentIdForDelete = $forDelete[$i]['agentIdForDelete'];
$profileIdForDelete = $forDelete[$i]['profileIdForDelete'];
$sql = "DELETE FROM LIVEPERSON_USERPROFILES
WHERE agentId = $agentIdForDelete AND profileId NOT IN ($profileIdForDelete)";
$stmt = Conexao::getConnection()->prepare($sql);
$stmt->execute();
}
That was the way I found to solve the problem. If anyone has another suggestion, i'm available :D
I'm looking to insert values from two sources (variables and a field from another table) into a new table. After some research, I found that this was possible, but cannot figure out how to accomplish this with my query.
Let me know if I have not provided enough context or code.
//Query to INSERT data
$query3 = "INSERT INTO `Checked_Out` (`name`, `quantityCheckedOut`, `checkedOut`, `returnDate`, `image`, `ID`) VALUES ('$name', '$quantityTaken', '$checkedOut', '$returnDate', '$ID')
SELECT `image` FROM `Checked_In` WHERE `ID` = '$ID'";
Try this:
$query3 = "INSERT INTO `Checked_Out` (`name`, `quantityCheckedOut`, `checkedOut`, `returnDate`, `image`, `ID`)
SELECT '$name', '$quantityTaken', '$checkedOut', '$returnDate', `image`, '$ID' FROM `Checked_In` WHERE `ID` = '$ID'";
Here's my code:
$con=mysqli_connect("localhost","name","pass","bird") ;
$result = mysqli_query($con,"SELECT * FROM bird");
mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values (0,'d','cwer','73')");
the first time, I could see the the values were added but when I reloaded, it didn't do any more, is it supposed to be like this ?
So if I want it to run every time I reload, how can I do that?
You probably have a unique constraint against your id column (or another column in that query) and when you try to add a second row using the same ID it is rejected by MySQL.
You should be doing error checking in your code. You should be checking to see how many rows were affected by your insert (using mysqli_affected_rows()) and, if the number is zero, getting the error message from MySQL (using mysqli_error()).
$result = mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values (0,'d','cwer','73')");
if (mysqli_affected_rows() === 0) {
echo mysqli_error($con);
}
#DaveChen's comment above is a good solution to your (potential) problem. If it isn't already, make your id column auto increment and then leave it out of your query.
mysqli_query($con,"INSERT INTO 'bird' (`name`, `latin`, `number`) values ('d','cwer','73')");
If your id column is aut_increment and unique: change your code to:
$con=mysqli_connect("localhost","name","pass","bird") ;
$result = mysqli_query($con,"SELECT * FROM bird");
mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values ('','d','cwer','73')");
This is what I am able to do:
When a user fills out a form to sign up the script will insert sign up info into table ps_reg_users. This table contains basic profile information.
I have added a Badge/Achievement section to display badges based on certain criteria.
What I need to do:
Once the user signs up, add that user to another table ps_badges with the id from the first query.
The id is set to auto increment on table ps_reg_users and inserts NULL upon submit, thus assigning the next id.
How would I INSERT a query to ps_reg_users then retrieve the id after it creates it to make another query based on that id?
PHP
$query = "INSERT INTO `" . DB_PREFIX . "reg_users` ( `id` , `first_name` , `last_name` , `password` , `email` , `date_time` , `user_status`, `verify_code` , `reward_points`, `ref_user`)
VALUES (NULL , '$first_name', '$last_name', '$password', '$e_email', '$date_time' , 'y', '$verify_code', '0' , '$ref_uid')";
This ^ works.
I need to execute this right after
$query = "INSERT INTO `" . DB_PREFIX . "badges` ( `user_id` , `pts_reputation` , `pts_comments` , `pts_uploads` , `pts_downloads` , `pts_featured` , `pts_activity`, `pts_refer`, `pts_donator` , `pts_country`)
VALUES (NULL , '0', '0', '0', '0', '0', '0', '0', '0', NULL)";
I hope im not over explaining, I think I need to tap into LAST_INSERT_ID() but how would I get it from the first query?
Basic sequence:
$sql = "INSERT ....";
$result = mysql_query($sql) or die(mysql_error());
$id = mysql_insert_id();
$sql = "INSERT .... (id,...) VALUES ($id, ...);"
$result = mysql_query($sql) or die(mysql_error());
Of course, you're still using an obsolete interface and SHOULD be switching to mysqli or PDO.
mysql_insert_id(); mysql function returns last inserted id
Wondering if there is a shorthand version to insert a new record into a table that has the primary key enabled? (i.e. not having to include the key column in the query)
Lets say the key column is called ID, and the other columns are Fname, Lname, and Website
$query = "INSERT INTO myTable VALUES ('Fname', 'Lname', 'Website')";
Use the DEFAULT keyword:
$query = "INSERT INTO myTable VALUES (DEFAULT,'Fname', 'Lname', 'Website')";
Also, you can specify the columns, (which is better practice):
$query = "INSERT INTO myTable
(fname, lname, website)
VALUES
('fname', 'lname', 'website')";
Reference:
http://dev.mysql.com/doc/refman/5.6/en/data-type-defaults.html
I prefer this syntaxis:
$query = "INSERT INTO myTable SET fname='Fname',lname='Lname',website='Website'";
$query = "INSERT INTO myTable VALUES (NULL,'Fname', 'Lname', 'Website')";
Just leaving the value of the AI primary key NULL will assign an auto incremented value.
This is phpMyAdmin method.
$query = "INSERT INTO myTable
(mtb_i_idautoinc, mtb_s_string1, mtb_s_string2)
VALUES
(NULL, 'Jagodina', '35000')";
You can also use blank single quotes for the auto_increment column. something like this. It worked for me.
$query = "INSERT INTO myTable VALUES ('','Fname', 'Lname', 'Website')";