简体   繁体   中英

How can I insert data from one table to another table after insert a data in first table?

Please Help me,

How can I insert data from one table to another table after insert a data in first table? I wrote a query but it has problem, It said "Unknown column 'test.ProjectNumber' ". should I define it first? I want insert data to test.ProjectNumber from test2.PN Please help me

Code:

    /**
 * Insert a record on another table
 */

// SQL statement parameters
$insert_table  = 'test2';    
$insert_fields = array(  
     'test2.PN' => 'test.ProjectNumber',
 );

// Insert record
$insert_sql = 'INSERT INTO ' . $insert_table
    . ' ('   . implode(', ', array_keys($insert_fields))   . ')'
    . ' VALUES ('    . implode(', ', array_values($insert_fields)) . ')';

sc_exec_sql($insert_sql);

Your SQL is evaluates as follows:

INSERT INTO test2 ( test2.PN ) VALUES ( test.ProjectNumber );

This is not valid because test.ProjectNumber is not understood in this context.

I think what you need to do is two separate insert statements as follows:

-- assumes that the number has not been inserted into test2 yet, 
-- just insert the same value into both tables:
INSERT INTO test2 ( test2.PN ) 
VALUES ( somevalue );

INSERT INTO test ( test.ProjectNumber )
VALUES ( somevalue );

or if the first row has already been inserted (it's not clear form your question), you can select that value and insert it, but you need to be able to identify the row (I'm using 123 )

-- If test2 already contains the row you need to insert from
-- then you need to select that row to insert the new row in test
INSERT INTO test ( test.ProjectNumber )
SELECT test2.PN
FROM test2
WHERE test2.Id = someid;

Hopefully this helps - I haven't translated this into php for you, partly as an exercise for you, but partly because my php is pretty rusty...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM