0

I am trying to select data from one table and insert it into an existing table using PHP.

While i understand that i could just collect the results into an array and then re-inject them into the correct table this seems inefficient. I must be able to just copy the requested query into a table of my choosing.

Any guidence would be much appreciated. Below is how i would put data into an array.

<?php
header("Cache-Control: no-cache");
date_default_timezone_set('Europe/London');

// open DB connection
require_once("DbConnect.php");

// fetch playlist
$result = $db->query(
    "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`, `picture` "
   ."FROM historylist  ORDER BY `date_played` DESC LIMIT 5 ");

// put into array
while ($row=$result->fetch_object()) $list[] = $row;



?>
Justin
  • 135
  • 2
  • 12

1 Answers1

1

As @tkausl says, if you are working with the same database, you can insert the result into the desired table with the same query.

<?php
header("Cache-Control: no-cache");
date_default_timezone_set('Europe/London');

// open DB connection
require_once("DbConnect.php");

// fetch playlist
$result = $db->query(
    "INSERT INTO my_table(`artist`, `title`, `label`, `albumyear`, `date_played`, `duration`, `picture`)" .
    "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`, `picture` " .
    "FROM historylist  ORDER BY `date_played` DESC LIMIT 5 ");
Sergio Flores
  • 5,231
  • 5
  • 37
  • 60
  • It's usually better to post just the part of the question that's changed, not the whole thing. – tadman Nov 28 '14 at 20:46
  • @byoigres Blimey, i should read the manual. I was trying to SELECT the data before i was telling it where to INSERT it INTO.. Many thanks! – Justin Nov 28 '14 at 21:00