moving rows to another table and also inserting additional values - php

Im currently moving rows from "mycart" table to "itemorders" table.
$query = "INSERT into orders
(email,address,postalcode,contactNo,orderdate,status) values
('".$email."','".$address."','".$postalcode."','".$contactNo."','".$orderdate."','".$status."');";
$query .= "INSERT into itemorders (itemID,itemName,itemSize,itemPrice,quantity) SELECT itemID,itemName,itemSize,itemPrice,quantity FROM mycart WHERE email='".$email."' ";
$result = mysqli_multi_query($conn,$query);
$ordersID = mysqli_insert_id($conn);
Currently, i have an additional field called ordersID in "itemorders" table, the first query also Auto increments a ordersID. I want to insert the $ordersID value that i have used in the first query into the second query. How can i do that?

Use the LAST_INSERT_ID() function in MySQL. It gets the last auto-increment ID, just as mysqli_insert_id() does.
$query .= "INSERT into itemorders (itemID,itemName,itemSize,itemPrice,quantity,orderSID)
SELECT itemID,itemName,itemSize,itemPrice,quantity, LAST_INSERT_ID()
FROM mycart
WHERE email='".$email."' ";

Related

INSERT into MYSQL and then before closing the connection select the insert id and then adding this id to 3 other tables

I am pretty new to the world of SQL so sorry for my ignorance on this.
I have a form on an admin page that adds a player to a team database. When the form is submitted what I need to have happen is:
The player gets inserted into players table (player_id is Primary key and used in next step).
A select statement runs to get the player_id.
Then inserts that into 2 other tables:
team_players and cards.
Below is the best representation of what I have tried:
if(isset($_POST['submit'])){
$first_name = mysqli_real_escape_string($con2, $_POST['first_name']);
$last_name = mysqli_real_escape_string($con2, $_POST['last_name']);
$email = mysqli_real_escape_string($con2, $_POST['email']);
$validation_code = md5($email + microtime());
$sql0 ="INSERT INTO players
(first_name, last_name, email, validation_code)
VALUES ('$first_name', '$last_name','$email', '$validation_code')";
$sql01 = "SELECT player_id FROM players WHERE email='$email'";
$result01 = $con2->query($sql01);
if ($result01->num_rows > 0) {
$row01 = $result01->fetch_assoc();
$playerID = $row01['player_id'];
echo $playerID; //In for debugging. Sometimes it works sometimes it doesn't
$sql02 = "INSERT INTO team_players, cards (player_id, team_id)
VALUES('$playerID', '$id')";
Thanks for any help on this.
You cannot insert into two tables using one query.
You can use a transaction and have both of them be contained within one transaction.
Otherwise execute two separate queries for each insertion.
One more thing, you have not executed the query for inserting to first table
START TRANSACTION;
INSERT INTO team_players (player_id, team_id) VALUES (...);
INSERT INTO cards (player_id, team_id) VALUES (...);
COMMIT;

PHP insert into database query

I am trying to insert values into a database table, a row is inserted but blank no values are inserted. Only the order_id which is the primary key with auto increment increase.
php code:
<?php
$user_get = mysql_query("SELECT * FROM users");
while($row_user = mysql_fetch_assoc($user_get)){
if($row_user['username'] == $_SESSION['username']){
$row_user['first_name'] = $res1;
$row_user['last_name'] = $res2;
$store_order ="INSERT INTO oko (user, product) VALUES ('$res1', '$res2')";
mysql_query($store_order);
}
}
?>
Your assignments are backwards. I think you meant to:
$res1 = $row_user['first_name'];
$res2 = $row_user['last_name'];
Don't you mean:
$res1 = $row_user['first_name'];
$res2 = $row_user['last_name'];
You could also update the SELECT to have a WHERE clause that checks $_SESSION['username'].
You could also just do an INSERT/SELECT:
INSERT INTO oko (user, product)
SELECT
first_name, last_name
FROM
users
WHERE
username = '$_SESSION["username"]'
Your code is vulnerable to injection. You should use properly parameterized queries with PDO/mysqli

Retrieve id of each INSERT statement in multi query

Is it possible to retrieve id (ua_id is in my case) for each INSERT statement in following SQL request
INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,1);
INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,2);
INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,3);
using mysqli::multi_query() to execute it wheres ua_id is AUTO_INCREMENT primary key?
In MySQL you can use LAST_INSERT_ID() function. You need to use this function each time - after INSERT statement. It gets ID for the last inserted record.
MySQL documentation - LAST_INSERT_ID()
Well. you do a multiquery, let's use it:
<?php
$db->multi_query('
INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,1);
SELECT LAST_INSERT_ID();
INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,2);
SELECT LAST_INSERT_ID();
INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,3);
SELECT LAST_INSERT_ID()') or trigger_error($db->error);
do {
if ($result = $db->store_result()) {
while ($row = $result->fetch_row()) {
var_dump($row);
}
}
} while ($db->next_result());
Do you mean lastInsertId?
http://cl1.php.net/manual/en/mysqli.insert-id.php
hope it helps!
mysqli->insert_id will return the ID of the first row inserted if you insert in the same table you then know that the next row inserted is the first row insert_id + 1...
If you work with many tables at once you then need to scroll back your results then you need to create another query using :
SELECT MAX(id) FROM table-a WHERE 1
...
SELECT MAX(id) FROM table-n WHERE 1
Now I don't know what is better (single insert query or multi query)...
Yes. Use $mysqli->insert_id - see working example below.
$mysqli = new mysqli(host, user, pass, db);
$query = "INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,1); ";
$query .= "INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,2); ";
$query .= "INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,3); ";
if ($mysqli->multi_query($query)) {
do {
/* Returns the auto generated id used in the last query */
printf("%d\n", $mysqli->insert_id);
/* Check if loop should continue */
if ($mysqli->more_results() === FALSE) break;
} while ($mysqli->next_result());
}
Use built in mysqli::$insert_id - documentation: http://php.net/manual/en/mysqli.insert-id.php

Get database row after insert in one query

At the moment I have a script where I add data to the database.
Once the data is entered I would like to get the get the row straight away.
For example if I have a query like this where I have two seperate:
$sql = "INSERT INTO table SET columnA '".$this->db->escape($columnA)."'";
$query = $this->db->query($sql);
$sql = "SELECT * FROM table";
$query = $this->db->query($sql);
return $query->db->row;
I want to be able to make get that database row instantly after inserting it. Will I have to make a whole new query or is there a quicker way? I am using OpenCarts API if that helps.
Thanks
Peter
INSERT INTO table (a,b,c) VALUES ('a','b','c');
SELECT * FROM table WHERE your_table_primary_key = LAST_INSERT_ID();
PHP:
$sql = "INSERT INTO table SET columnA '".$this->db->escape($columnA)."';";
$sql .= "SELECT * FROM table WHERE your_table_primary_key = LAST_INSERT_ID();"
$query = $this->db->query($sql);
return $query->db->row;

help with multiple queries (PHP/MySQL)

PLease note I am a beginner.
My situation is thus:
I am trying to run multiple queries, off the back of a dynamic form. So the data is going to end up in two different tables.
I am currently successfully storing in to my item_bank, which has an auto_increment itemId.
I then want to grab the ItemId just created on that last query and insert it into my next query of which I am also inserting an array. (I hope you can follow this)
first off, is it even possible for me to run multiple queries like this on a single page?
Below is my attempt at the queries. Currently the first query works, however I cannot get the ItemId generated from that query.
$answers is an array.
// store item structure info into item_bank_tb
$query = "INSERT INTO item_bank_tb (item_type, user_id, unit_id, question_text, item_desc, item_name)
VALUES('$type','$creator','$unit','$text','$desc','$name')";
mysql_query($query) or die(mysql_error());
$itemid = mysql_insert_id();
//now store different answers
$query = "INSERT INTO answers_tb (item_id, text_value)VALUES('$itemid',' . implode(',', $answers) . ')";
mysql_query($query) or die(mysql_error());
this is the error i get now: "Column count doesn't match value count at row 1"
To get the ID generated by an auto-increment field in PHP/MySQL just use the mysql_insert_id() function.
Edit:
// store item structure info into item_bank_tb
$query = "INSERT INTO item_bank_tb (item_type, user_id, unit_id, question_text, item_desc, item_name)
VALUES('$type','$creator','$unit','$text','$desc','$name')";
mysql_query($query) or die(mysql_error());
$itemid = mysql_insert_id();
//now store different answers
$answers = mysql_real_escape_string(implode(',', $answers));
$query = "INSERT INTO answers_tb (item_id, text_value) VALUES('$itemid','$answers')";
mysql_query($query) or die(mysql_error());
Have a look at mysql_insert_id():
// store item structure info into item_bank_tb
mysql_query($query);
$itemid = mysql_insert_id();
// now store different answers

Categories