简体   繁体   中英

php SQL query inserting records in wrong column

I have this code to select data from one table and move it to another one while in array.

<?php 
// CHANGE THE CONNECTION INFORMATION TO YOUR DETAILS (OFF YOU CARD)
//$connection = mysql_connect("localhost","root");


$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
$conn->Open("Provider=SQLOLEDB; ..");

$conn2 = new COM("ADODB.Connection") or die("Cannot start ADO");
$conn2->Open("Provider=SQLOLEDB; Data Source=...;
Initial Catalog=...; User ID=...; Password=...");


$rs = $conn->Execute("SELECT ColourID, Width, Height, Price FROM VS_Matrix");    // Recordset

$num_rows = $rs->Fields->Count();

for ($i=0; $i < $num_rows; $i++) {
    $fld[$i] = $rs->Fields($i);
    $fld2[$i] = $rs->Fields($i);
    $fld3[$i] = $rs->Fields($i);
    $fld4[$i] = $rs->Fields($i);
    $x= 469;


}

$rowcount = 0;
while (!$rs->EOF) {
    for ($i=0; $i < $num_rows; $i++) {
        echo $fld[$i]->value . "\t";

$rs2 = $conn2->Execute("INSERT INTO TST (ID, ColourID, Width, Height, Price) VALUES ('".$x."','".$fld[$i]."','".$fld2[$i]."','".$fld3[$i]."','".$fld4[$i]."')"); 

    }




    echo "\n";
    $rowcount++;   
        $x=$x+1;     // increments rowcount
    $rs->MoveNext();
}

$rs->Close();
$conn->Close();

$rs = null;
$conn = null; 

For some reason its placing records seemingly at random probably cause I made a silly mistake. Anyone can spot it?

From PHP manual user comments PHP: COM - Manual :

    $rows=0;
    while(!$rs->EOF) {
        for($i=0;$i<$rs->Fields->count;$i++) {
            $rsf = $rs->Fields($i);
            if($associative) $rtn[$rows][$rsf->Name] = $rsf->value;
            else $rtn[$rows][$i] = $rsf->value;
        }
        $rows++;
        $rs->MoveNext();
    }

After this you'll have $rtn where $rtn[$row] - is an array which consist of values of one row of database.

Based on your question, I'm not sure why you're doing all this extra work. Assuming ID is an AUTO_INCREMENT you can just:

INSERT INTO TST (ColourID, Width, Height, Price) 
SELECT ColourID, Width, Height, Price FROM VS_Matrix

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM