how to select id from one table and insert into other table - php

$select = "SELECT MAX(order_id) FROM `order`";
mysql_query($select);
foreach ($_COOKIE['item'] as $key12 => $value) {
$value22 = explode("__", $value);
$query1 = "INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$value22[3]','$value22[4]')";
$result2 = mysql_query($query1);
The output of this is SELECT MAX(order_id) FROM order, so what is the solution of this selection and insertion of the id

$select="SELECT MAX(order_id) FROM `order`";
$row = mysqli_query($con,$select);
if(mysqli_num_rows($row)>0)
{
while($data = mysqli_fetch_assoc($row))
{
$order_id = $data['order_id'];
}
}
//This way you can fetch data
Then use this while inserting value for order_id in your query as in
$query1="INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$order_id','$value22[4]')";

one another way to find last inserted id from the db connection:
mysql_query('INSERT INTO order(a) VALUES('b'));
$id = mysql_insert_id();
then $id will be last inserted id

Recommendation:
Use only one batch INSERT query. It gives you the opportunity to insert multiple rows at once, e.g. by running only one query. And is a lot faster.
Used method:
Extract maximum of order_id from order and assign to $maxOrderId.
Iterate through cookie items and build corresponding rows
part of the INSERT sql statement. Then add it to the array $insertRowValues.
In the end implode the $insertRowValues array into the batch INSERT statement.
Run the batch INSERT query - only once.
<?php
$select = "SELECT MAX(order_id) FROM `order`";
$maxOrderId = mysql_query($select);
$insertRowValues = array();
foreach ($_COOKIE['item'] as $key12 => $value) {
$value22 = explode("__", $value);
$insertRowValues[] = "('', " . $value22[5] . ", '" . $maxOrderId . "', '" . $value22[3] . "', '" . $value22[4] . "')";
}
$query1 = "INSERT INTO `cart`
(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`)
VALUES " . implode(', ', $insertRowValues);
$result2 = mysql_query($query1);
Other recommendations:
Use mysqli or PDO instead of mysql, because mysql is already removed as of PHP 5.5.0 (see MySQL Library - Introduction);
Use exception handling;
Use prepared statements to avoid MySQL injection.
P.S: I couldn't test anything.
Good luck!

Related

Check PostgreSQL tables before insertion

I have to insert several values in a PgSQL Table using these variables
$knr = $reader->getAttribute('Nr');
$kname = $reader->getAttribute('Name');
And this insertion code:
$SQL = "";
$SQL .= "SELECT
(konzern).knr AS knr, (konzern).name AS name
FROM konzern";
$SQL .= "INSERT INTO konzern (";
$SQL .= "knr, name";
$SQL .= ") VALUES (";
$SQL .= "'".$knr."', '".$kname."'";
$SQL .= ");".PHP_EOL;
And I want to check if the table "Konzern" already have a row with the $knr and if yes it should insert into this, if not it should create a new row
$query = doQuery("select nr from konzern where knr = '".$knr."'");
$num_rows = ($query->num_rows);
if ($num_rows > 0) {
// do nothing
}
else {
$sql .= "select nextval('konzern_nr_seq')";
}
But I have some problems puting this into the right order.
Can someone complete this code?
You can do this with a single query in this way :
INSERT INTO konzern SELECT val1, val2
WHERE NOT EXISTS(
SELECT nr from konzern where knr = 'var1'
)
Implement this approach it will be more straigth forward .
And remember to use query parameters instead of concatenating the query text, to avoid SQL Injections.

Query does not work when i fetch data and insert it into a table

I am trying to insert to another table the results of a select statement from another table. The select statement works but the insert statement does not work. Please help me.
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
}
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
header("Location:homeclient.php");
?>
You asked for how to do these two as one query.
This is how:
$query = mysql_query("INSERT INTO `client` ( `client_csub_code`, `client_csub_name`, `client_csub_day`, `client_csub_time` ) SELECT `sub_code`, `sub_name`, `sub_day`, `sub_time` FROM `subject` WHERE `code` = '$enrol'");
// I would also add error checking
if ( mysql_errno() )
echo mysql_error();
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
}
header("Location:homeclient.php");
?>
Try changing to this. Currently your query is outside of your while, it will only run once and the values of $csubject etc are always going to be the last values of your fetched results.

i want to insert data of a variable in two columns continuously

<?php
$db = mysql_connect('localhost', 'root', '') or
die ('Unable to connect. Check your connection parameters.');
mysql_select_db('my_db', $db) or die(mysql_error($db));
$query = 'SELECT
second, count(*) FROM tb_one GROUP BY second';
$result = mysql_query($query, $db) or die(mysql_error($db));
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $value) {
$queryy = 'INSERT INTO tb_two (name) VALUES ("' . $value . '")';
mysql_query($queryy, $db) or die(mysql_error($db));
}
}
?>
In this script first query is meant to select and count duplicate values(that works well), But in second query I want to insert the selected data in another table which has two columns, first column for its name and second column for its count of duplicate...If there is one column in the insert statement it works well and adds values. But I want two columns- one for name and one for its counted number of duplicates. thank you sir...I have been trying it for many days..
You can do this all in MySQL:
INSERT INTO tb_two(name, count)
SELECT second, count(*)
FROM tb_one
GROUP BY second;
Though, in other news the mysql_ functions have been deprecated. You should be using the PDO Library. Or at least the MySQL Improved Library.
Make your life easier by aliasing the duplicate column, so you can address it more easily.
Here is how:
Replace this
$query = 'SELECT second, count(*) FROM tb_one GROUP BY second';
by this:
$query = 'SELECT second, count(*) as duplicates FROM tb_one GROUP BY second';
You now have "duplicates" as the column name. Then you can use it, like this for example:
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $r) {
$queryy = "INSERT INTO tb_two SET name='".$r['second']."', duplicates='".$r['duplicates']."'";
mysql_query($queryy, $db) or die(mysql_error($db));
}
}
Try this, sorry if it has a syntax issue, I did it in notepad.
while ($row = mysql_fetch_assoc($result))
{
$query = "INSERT INTO tb_two (column1, column2) VALUES ('" . $row[0] . "', '" . $row[1] . "')";
mysql_query($query, $db) or die(mysql_error($db));
}

Insert data array in SQL after searching from another SQL table

I have an array $members that contains some ID(maximum 6 in number) from the table users. Using the following code, I loop through each index of $members, search for the details and store them in another array.
foreach($members as $key=>$value){
$res = mysql_query("SELECT id,name,email FROM users WHERE id='$value'");
if ($res === false) {
echo mysql_error();
die;
}
$row = mysql_fetch_assoc($res);
if($row['id'])
{
$members_name[]=$row['name'];//array for name
}
}
Now I want to insert the ID & names that are stored in the array into another TABLE register in the following format:
(The left side are the rows in my TABLE register)
mem_0_id-->$members[0]
mem_0_name-->$members_name[0]
mem_1_id-->$members[1]
mem_1_name-->$members_name[1]
mem_2_id-->$members[2]
mem_2_name-->$members_name[2]
mem_3_id-->$members[3]
mem_3_name-->$members_name[3]
mem_4_id-->$members[4]
mem_4_name-->$members_name[4]
How can I insert in this way? using just a single INSERT statement?
haven't tried this, but here is my answer anyway :)
$query = "INSERT INTO register(id, name) VALUES ($members[0], $members_name[0])";
for($i=1; $i<count($members); $i++)
{
$query .= ", ($members[$i], $members_name[$i])";
}
then try to execute the query..
Do you do anything else with the array, or are you just retrieving it from one table in order to insert it into another?
If so then you can do the whole thing like this.
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "insert into register (id, name) select id, name from users where id in ($memberIds)";
mysql_query($query); // this will select and insert in one go
If you do need to keep the array in memory, then it's still a good idea to get it all out at once
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "select id, name from users where id in ($memberIds)";
$res = mysql_query($query);
while ($row = mysql_fetch_assoc($res)) {
$memberData[] = $row;
}
That's because running a query inside a loop is very bad for performance. Every time you run a query there is an overhead, so getting all the data at once means you pay this overhead once rather than multiple times.
Then you can build a statement to insert multiple rows:
$sql = "insert into register (id, name) values ";
$sql .= "(" . $memberData[0]['id'] . "," . $memberData[0]['name'] . ")";
for($i = 1; $i < count($memberData); $i++) {
$sql .= ",(" . $memberData[$i]['id'] . ",'" . $memberData[$i]['name'] . "')";
}
mysql_query($sql);
It's a bit nasty because of the commas and quotes but if I've done it correctly then if you do
echo $sql;
you should get something like
insert into register (id, name) values (1, 'john'), (2, 'jane'), (3, 'alice');
You can see that the first way, where you select and insert in one statment, is a lot nicer and easier so if you don't do anything else with the array then I highly recommend doing it that way.

inserting values from a loop

$sql1 = "SELECT SIDno FROM class WHERE SubjID='$SubjName' and SecID='$SecName'";
$result1 = mysql_query($sql1);
while ($row1 = mysql_fetch_assoc($result1)){
$IDno = $row1["SIDno"];
$sql2="INSERT INTO registered ( ServiceID, IDno, Stype)VALUES('$RecCode','$IDno','$Stype')";
}
this is my code. its working but it only insert one data into the database. How can make it away to insert all the possible data from the loop. Can anyone help me?
You’re probably executing the query after the loop so only the last record is being inserted.
Try to execute the insertion query at the end of the loop:
while ($row1 = mysql_fetch_assoc($result1)) {
$IDno = $row1["SIDno"];
$sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ('".mysql_real_escape_string($RecCode)."', '".mysql_real_escape_string($IDno)."', '".mysql_real_escape_string($Stype)."')";
mysql_query($sql2);
}
Or you first collect all data and then do one query to insert all records:
$values = array();
while ($row1 = mysql_fetch_assoc($result1)) {
$IDno = $row1["SIDno"];
$values[] = "('".mysql_real_escape_string($RecCode)."', '".mysql_real_escape_string($IDno)."', '".mysql_real_escape_string($Stype)."')";
}
if (!empty($values)) {
$sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ".implode(',', $values);
mysql_query($sql2);
}
But don’t forget to prepare the values for the query (see mysql_real_escape_string function).
If you are not planing to do anything with the fetched data, you could use INSERT .. SELECT .. statement.
Example:
INSERT INTO registered (ServiceID, IDno, Stype)
SELECT field1, field2, field3
FROM class
WHERE SubjID='$SubjName' and SecID='$SecName'"
And like written before me, escape your variables...
Note: make sure you're escaping your variables with mysql_real_escape_string.
$sql1 = "SELECT SIDno FROM class WHERE SubjID='$SubjName' and SecID='$SecName'";
$result1 = mysql_query($sql1);
$sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ";
$addComma = false;
while ($row1 = mysql_fetch_assoc($result1)){
$IDno = $row1["SIDno"];
$sql2 .= ($addComma ? ", " : "") . "('$RecCode','$IDno','$Stype')";
$addComma = true;
}
Change this line:
$sql2="INSERT INTO registered..."
to this:
$sql2 .= "INSERT INTO registered..."
inside the loop. You are accidentally overwriting the insert statement each time. If you use .= you will append the next statement to the previous one, creating a batch of insert scripts, one for each record.

Categories