insert records from one table to another - php

Hi I am trying to add records from one table to another, once i have added a 'user' record, the table that is being selected contains rows of available security options, and the table that is being inserted to is the child table for the user, detailing security options.
I cam across this code in an earlier post, which i am sure works nicely, however i am trying to modify it so that the values from statement, includes two parts, one from the select query and one which is the key from the master record.#
This is the original code I found from this site:
INSERT INTO def (catid, title, page, publish)
SELECT catid, title, 'page','yes' from `abc`
And this is what I am trying to do with it:
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) values ('".$keys["UserPk"]."', SELECT ModulePk from Global_Modules)";
CustomQuery($sql);
And this is the error I am getting:
INSERT INTO Link_UserSecurity (UserFk, ModuleFk) values ('4', SELECT
ModulePk from Global_Modules)
See screenshot for further detail
Obviously I am not concating the from statement properly, but would appreciate any help?

You can insert the $keys["UserPk"] variable as if it were a constant in the SQL:
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) SELECT '{$keys["UserPk"]}', ModulePk from Global_Modules";
Do note that $keys["UserPk"] must be escaped before adding it into the query. In PDO, it would look like this:
$keys["UserPk"] = $pdo->quote($keys["UserPk"]);
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) SELECT '{$keys["UserPk"]}', ModulePk from Global_Modules";

Could be a problem related to the double quotes sequence
"INSERT INTO Link_UserSecurity (UserFk, ModuleFk)
values ('". $keys['UserPk']. "', SELECT ModulePk from Global_Modules)";
but you could use also a select insert
"INSERT INTO Link_UserSecurity (UserFk, ModuleFk)
SELECT '" . $keys['UserPk']. "' , ModulePk from Global_Modules)";

Adding only new and unique records from one table to another. Limiting is a good idea to prevent it from timeout. It can be run several times until all the records copied.
First, select the latest record ID from the table to be copied:
SET #lastcopied =
(SELECT
IF(MAX(a.exp_inotech_id)>0, MAX(a.exp_inotech_id), 0) AS lastcopied
FROM
kll_export_to a
WHERE exp_tezgah = 'A2015-0056');
Then, select and add the records to the destination table:
INSERT INTO kll_export_to
(SELECT * FROM
kll_export_from f
GROUP BY f.exp_inotech_id
HAVING COUNT(f.exp_inotech_id) = 1 AND exp_tezgah = 'A2015-0056' AND f.exp_inotech_id > #lastcopied
ORDER BY exp_inotech_id
LIMIT 1000);

Related

Insert data with MAX(id) and values of status at the same time

I was trying with this code but it didn't work. it's always get the MAX(eq_no) as 0
$sql1 =mysqli_query($con, "SELECT MAX(eq_no) AS val FROM tech_add_equip");
$sql2 = "INSERT INTO time (eq_no,status_no) VALUES ('$val', 4 );";
if (!mysqli_query($con,$sql2)) {
die('Error: ' . mysqli_error($con)); };
Finally, after I try with this code, it inserts in the right number of MAX(eq_no) but i still cant insert the values of status_no
INSERT INTO time (eq_no) SELECT MAX(eq_no) AS vale FROM tech_add_equip
Could you suggest me what did i missing in the code?
Thank you for your helping
One row returned from SELECT a,b,c statement in sub query is equivalent to set of values that is otherwise hardcoded as ('a-value','b-value','c-value')*. You can hardcode a value within select as well:
INSERT INTO time (eq_no, status_no)
SELECT MAX(eq_no), 4
FROM tech_add_equip
No need for aliases within select - order of columns matters.
*) One row result can be used for IN() clause. Another row would become set of values after comma - can't be uset for IN(), but it works ok for INSERT
('row1-a-value', 'row1-b-value'), ('row2-a-value', 'row2-b-value')
$max = SELECT MAX( customer_id ) FROM customers;
INSERT INTO customers( customer_id, statusno )
VALUES ($max , 4)

insert value from one table into another whilst doing a double insert

Not sure that this is even possible. I am inserting values into two tables at the same time using multi_query. That works fine. One of the tables has an auto increment column and I need to take the last auto incremented number and insert it into the second table so like this: insert into table 1 then take the last inserted number from column X and insert it along with other data into table 2. I have played around with using SELECT LAST and INSERT INTO but so far its just doing my head in. The insert statements looks like this:
$sql= "INSERT INTO tbleClients (riskClientId, riskFacility, riskAudDate) VALUES ('$riskclient2', '$facility2', '$riskdate2');";
$sql .="SELECT LAST(riskId) FROM tbleClients;";$sql .="INSERT INTO tblRiskRegister (riskId) SELECT riskId FROM tbleClients ;";
$sql .= "INSERT INTO tblRiskRegister (riskAudDate, riskClientId, riskSessionId, RiskNewId) VALUES ('$riskdate2', '$riskclient2', '$sessionid', '$risknewid')";
Individually they all produce results but I need it to happen simultaneously. I did toy with the idea of doing them all separately but figure thats not very efficient. Any pointers would be appreciated.
$sql= "INSERT INTO tbleClients (riskClientId, riskFacility, riskAudDate) VALUES ('$riskclient2', '$facility2', '$riskdate2');";
After executing the above query, using mysqli_insert_id(), which gives you the last insert id.
So below query is useless.
$sql .="SELECT LAST(riskId) FROM tbleClients;";
$sql .="INSERT INTO tblRiskRegister (riskId) SELECT riskId FROM tbleClients ;";
You can insert last_insert_id in above query.
Unable to find the relation between above & below query.
$sql .= "INSERT INTO tblRiskRegister (riskAudDate, riskClientId, riskSessionId, RiskNewId) VALUES ('$riskdate2', '$riskclient2', '$sessionid', '$risknewid')";

Insert values in junction table

I have three tables in database:
trips(trip_id(pk), trip_name(unique), user_id(fk))
places(place_id(pk), place_name(unique))
trips_places_asc(trip_id(fk), place_id(fk))
Since, many trips can have many places, I have one junction table as above.
Now, if user insert places to the trip, the places will be added to places table and the trip will be associated with the places in trips_places_asc table.
So, if i write query like:
INSERT INTO places (place_name)
VALUES ('XYZ')
INSERT INTO trips (trip_name)
VALUES ('MyTrip')
Then, How to store trip_id and place_id in Junction or Association table trips_places_asc?
will I have to fire two queries? plz help.
Note: There are many questions on SO like this one and this one. but, none of them have accepted answer or not even an answer. so, plz do not mark as duplicate.
Since you have place_name and trip_name as unique just do as:
insert into trips_places_asc ( trip_id, place_id )
values ( (select trip_id from trips where trip_name = 'MyTrip'),
(select place_id from places where place_name = 'XYZ') );
Or depending what comand you are using to insert (php command I mean) you can return the ids after the inserts and use it to run an insert command with it.
It will be like: (using mysqli* functions )
$query = "INSERT INTO trips (trip_name) values ('MyTrip')";
$mysqli->query($query);
$trip_id = $mysqli->insert_id;
$query2 = "INSERT INTO places (place_name) values ('XYZ')";
$mysqli->query($query2);
$place_id = $mysqli->insert_id;
$query3 = "insert into trips_places_asc ( trip_id, place_id ) ";
$query3 .= " values ($trip_id, $place_id)";
Note, I'm doing this directly from my mind, so maybe you have to adjust some syntax error or be concerned about prepared statements.
EDIT
Though I should add the proper documentation link about this command: http://php.net/manual/en/mysqli.insert-id.php

PHP MySQL INSERT data from another table using the where clause and insert unique values to the same rows

I want to insert data from one table into another where one field equals another in both tables. So far this works. The problem is, I also need to insert additional data into those same rows that is not included on the first table.
//enter rows into database
foreach($_POST['sku'] as $row=>$sku)
{
//this is the data that needs to be added to the table
$item_sku=$sku;
$image="/$item_sku.jpg";
$small_image="/$item_sku.jpg";
$thumbnail="/$item_sku.jpg";
//currently this is what is working to import data from one table to the other
$sql= "INSERT INTO magento_import (sku, description, price)
SELECT PR_SKU, PR_Description, PR_UnitPrice
FROM products
WHERE PR_SKU = '$sku'";
//I need something here to add the above variables to the same row where PR_SKU = '$sku'
if (!mysql_query($sql))
{
die('Error: '.mysql_error());
}
echo "$row record added";
}
The columns for the missing data on magento_table are called 'image', 'small_image', and 'thumbnail'. This is simple a hack to put data from an old product table into a new product table, export as a CSV, and run a profile in Magento. I don't need to worry about SQL injections. It's something I'm running off of a local machine. I'm trying to avoid as much manual data entry as possible while switching products over to a new ecommerce system. Thanks for any help you can give.
Selecting literal values should do what you intend:
$sql= "INSERT INTO magento_import (sku, description, price, image, small_image, thumbnail)
SELECT PR_SKU, PR_Description, PR_UnitPrice, \"$image\", \"$small_image\", \"$thumbnail\"
FROM products
WHERE PR_SKU = '$sku'";
You can use another update statement to do this. I doubt if you can do this with one single query
foreach($_POST['sku'] as $row=>$sku)
{
//this is the data that needs to be added to the table
$item_sku=$sku;
$image="/$item_sku.jpg";
$small_image="/$item_sku.jpg";
$thumbnail="/$item_sku.jpg";
//currently this is what is working to import data from one table to the other
$sql= "INSERT INTO magento_import (sku, description, price)
SELECT PR_SKU, PR_Description, PR_UnitPrice
FROM products
WHERE PR_SKU = '$sku'";
//I need something here to add the above variables to the same row where PR_SKU = '$sku'
if (!mysql_query($sql))
{
die('Error: '.mysql_error());
}else {
$sql = "UPDATE magento_import SET item='$item',image='$image',small_image='$small_image',thumbnail='$thumbnail' WHERE PR_SKU = '$sku'";
echo "$row record added";
}
}
You can just add the variables directly to the query. As long as they are quoted they will work as simple values.
$sql= "INSERT INTO magento_import (sku, description, price, x, y, z)
SELECT PR_SKU, PR_Description, PR_UnitPrice, '$x' AS x, '$y' AS y, '$z' AS z
FROM products
WHERE PR_SKU = '$sku'";

Access last row added to table - PHP

I have a simple sql query adding a new row to a database and need it to return the a field back to Javascript. The field does Auto_increment but stupildy I called it 'itemId' so mysql_insert_id doesnt work and I don't think I have time to go and amend all the php files that use 'itemId'
Here's my code if it helps:
$addMainItem = "INSERT INTO newsItems (itemId, title, date, tags, location, latitude, longitude, visibleFrontpage, introText, fullDome, liveEvent, customServing, visitorAttraction, retail, digitalCinema, visiblePublic, thumbPath, links, smallDesc) VALUES ('','$title','$date','$tags','$loco','$lat','$long','$visiFront','$intro','$dome ','$live','$custom','$attrac','$retail','$cinema','$public','$thumbPath','$links','$smallDesc')";
$result = mysql_query($addMainItem) or die('error '.mysql_error());
if($result) echo (mysql_insert_id());
I've never heard that naming a column itemId breaking mysql_isert_id().
But you can just select the last inserted record if auto_increment is working.
SELECT * FROM newsItems ORDER BY itemId DESC LIMIT 1
You can put the select statement into a transaction with the insert statement if you're using innoDB and you're worried about a race condition.
mysql_query("SELECT LAST_INSERT_ID()");
Isn't it what are you looking for?

Categories