How to insert a complete row from another table through mysql query!


when we need to copy a row form one table to another table, where the new record has to be created on second table, we can do it directly with query instead of selecting all fields in php and then write the insert query.
The insert .. select query does the process.
Example:
tabl1 => { id, col1, col2, col3}
tabl2 => {nid, col1, col2, col3, date}
Here we need to select all data from a row from tabl1 and to insert it directly to tabl2
the query will be as below in case both tabl have Auto Incremented Fields ( like id and nid)
$sql = "INSERT INTO tabl2 (`col1`, `col2`, `col3`, `date`) SELECT col1, col2, col3, NOW() FROM tabl2 where id=3";
if
“INSERT INTO tabl2 select * from tabl1″
is used, then all fields will be selected and if no unique fields on tabl2 found then new record will created.
we can not IGNORE or Exclude a field when we use “SELECT * ” query. so all needed field values are to be written on query.

Comments

Popular posts from this blog

PHP / SQL Security – The Big Picture

PHP / SQL Security – SQL Commands and Non-String Variables

Top 50 Web Hacking Techniques