Question

I have 2 tables: STD and SMS. What I need to do is to select from table STD the copy the result to an array then insert each element of the array to another table, SMS.

Here's my code:

$query=mysql_query("Select from STD WHEre <my conditions>");
$result=mysql_fetch_array($query)
foreach($result as $value)
mysql_query("INSERT INTO SMS set SMS.column='$value'")

It is not updating the SMS table at all. Can someone here have a better idea or tell me what's wrong with the code? thanks.

No correct solution

OTHER TIPS

You about updating or inserting data? if You want to insert user JW already answered, else you must set condition on Your update query.

$query=mysql_query("Select from STD WHEre <my conditions>");
$result=mysql_fetch_array($query)
foreach($result as $value)
mysql_query("Update SMS set SMS.column='$value' where SMS.std_id = '{$value['id']}'"); /// fieldnames are my example, You must generate Your condition.. 

or You can use update from another table

try this, but this will update all the values of the table like your actual query does:

    $query=mysql_query("Update SMS set 
    SMS.column=(Select <column_name> from STD where <my conditions> limit 1)");

You can do that in just one query, use INSERT INTO...SELECT statement.

INSERT INTO SMS (col1, col2, ...., Coll3)
SELECT col1, col2, ...., Coll3
FROM STD

I presume you're trying to get all rows from the STD table and insert them into the SMS table, and that the SMS table definition is the same as the STD one?

If so, this should work:

$result = mysql_query('SELECT * FROM `STD` WHERE <my_conditions>');
while (($row = mysql_fetch_assoc($result)) !== FALSE) // Loop over all rows selected
{
  $columns = implode(', ', array_keys($row)); // returns string of column names e.g. "col1, col2, col3" etc.
  $values = "'" . implode("', '", array_values($row)) . "'"; // returns string of quoted values e.g. "'val1', 'val2', 'val3'"
  mysql_query("INSERT INTO `SMS` ($columns) VALUES ($values)"); // inserts the row into the SMS database table
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top