1

Hello I'm writing PHP and mysql. If I want to select then insert to database, I will

  • step1.Select from table
  • step2. mysqli_fetch_array and contain to variable such as $foo
  • step3. INSERT INTO MyTable (firstname) VALUES ('$foo')"

Is it possible that I select then insert without fetch from database?

doflamingo
  • 567
  • 5
  • 23
  • 1
    If there is no client-side work that needs to be done the "SELECT + INSERT" can be done entirely in SQL, without needing to fetch data back to PHP first. If PHP is required to do work on the data, then it must be fetched back, processed, and then sent onward to the INSERT. The question would benefit from an example case. – user2864740 Oct 27 '16 at 05:10
  • 3
    Follow this: http://stackoverflow.com/questions/9692319/how-can-i-insert-values-into-a-table-using-a-subquery-with-more-than-one-result – Teerath Kumar Oct 27 '16 at 07:06

2 Answers2

1

If you want to do this via mysql you can use

INSERT INTO Table2(field1, field2) 
SELECT old_field1 as field1, old_field2 as field2 FROM Table1

Just be sure that you match fieldnames with "as".

Hasan Veli Soyalan
  • 2,428
  • 20
  • 24
0

Its a very simple concept,

mysqli_fetch_array()

returns an array and you cannot directly store an array into a column of a table in database. Either you have to map with the table column or convert it into json to store it into table column.

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59