user5641678
user5641678

Reputation: 35

insert records from one table to another

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?

Upvotes: 2

Views: 68

Answers (3)

Hakan Ari
Hakan Ari

Reputation: 1

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);

Upvotes: 0

dotancohen
dotancohen

Reputation: 31471

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";

Upvotes: 2

ScaisEdge
ScaisEdge

Reputation: 133360

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)";

Upvotes: 0

Related Questions