RE: [PHP] array
| From: | Jay Blanchard | Date: | Wed, 08 Sep 2004 12:21:43 +0000 |
| Subject: | RE: [PHP] array | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-196115@lists.php.net to get a copy of this message | ||
[snip]
I'm reading data. Can I open a connection within a connection and write
data to another $db.$table or do I have to write my data to an array. In
an array, how do I do this?
I've looked at array_push, but don't think this is what I want?
$authors = array();
array_push($singleauthor,$mydata->id);
I've been reading http://ca3.php.net/manual/en/function.array-push.php
[/snip]
Here is some pseudo-code that may help...
$sqlSelect = "SELECT
foo FROM table1 WHERE condition ";
$sqlQuery = mysql_query($sqlSelect, $myConnection);
while($row = mysql_fetch_array($sqlQuery)){
echo $row['foo'] . "\n"; // so we can see foo
$sqlInsert = "INSERT INTO table2(newFoo) ";
$sqlInsert .= "VALUES('" . $row['foo'] . "') ";
$sqlInQuery = mysql_query($sqlInsert, $myConnection);
}
What is bad here is that an INSERT is called each time through the loop
for foo, which may be inefficient. As with anything PHP there is more
than one way to skin a cat though.
$arrayIndex = 0;
while($row = mysql_fetch_array($sqlQuery)){
$newFooArray[$arrayIndex] = $row['foo'];
$arrayIndex++;
}
for($i = 0; $i < count($newFooArray); $i++){
echo $newFooArray[$i] . "\n";
$sqlInsert = "INSERT INTO table2(newFoo) ";
$sqlInsert .= "VALUES('" . $newFooArray[$i] . "') ";
$sqlInQuery = mysql_query($sqlInsert, $myConnection);
}
Again, the INSERT is called each time.
There is one more way to do this, and it would all be in one query. This
the most efficient, especially if you do not have to manipulate the data
before placing it in the second table.
$sqlSelectAndInsert = "INSERT INTO table2 (newFoo) ";
$sqlSelectAndInsert .= "SELECT foo FROM table1 ";
$sqlSelectAndInsert .= "WHERE conditions ";
$sqlSIQuery = mysql_query($sqlSelectAndInsert, $myConnection);