ellis
ellis

Reputation: 53

PHP - loop through array and insert values to SQL

I have an excel file that I'm stripping down in AIR and converting to $ delimited string. I send that string to PHP ($pushFinal) and then use $array = explode("$",$pushFinal); to convert the string to an array. Now I want to loop through the array, inserting the values into SQL, mimicking the excel format. Each 'line' in excel is 49 columns, or 'values' so I need to insert 49 values at a time from the $array for each row in SQL.

What is the best way to do this?

I'm a rookie so have mercy on me :)

So, I tried this:

$pushFinal = $_POST["pushFinal"];
$lines = array();
$lines = explode("|",$pushFinal); 
$lineItems = array();


foreach ($lines as $val){
    $lineItems = explode("$",$val);
    $temp = "";
    foreach($lineItems as $val2){
        $temp = $temp."'".$val2."',";   
    }
    $sql="insert into OPS_SCHEDULE values($temp)";
    $stmt = sqlsrv_query($conn,$sql);
}

The INSERT is failing though. Does this look right? I delimited each line from excel with | and then delimited each value in that line by $. That shows up correctly in $pushFinal.

Upvotes: 1

Views: 3032

Answers (3)

ellis
ellis

Reputation: 53

OK, i got it.

$pushFinal = $_POST["pushFinal"];
$lines = array();
$lines = explode("|",$pushFinal); 
$lineItems = array();

foreach ($lines as $val){
    $lineItems = explode("$",$val);
    $temp = "";
    foreach($lineItems as $val2){
        $temp = $temp."'".$val2."',";   
    }
    $temp = substr($temp, 0, -1);
    $sql ="insert into table values($temp)";
    $stmt = sqlsrv_query($conn,$sql);
}

I had to remove the trailing "," from each $temp row. Thanks "lc" for helping me with delimiting rows separately from the values. That worked like a charm.

Upvotes: 0

Razvan
Razvan

Reputation: 10101

foreach($array as $val){
    $sqlVals[]="'".$val."'";
}
$sqlValsStr = implode(",",$sqlVals);
$sql = "insert into table values(".$sqlValsStr.")";

Upvotes: 1

quickshiftin
quickshiftin

Reputation: 69781

Just read any basic PHP/MySQL introduction page on the internet and you'll have the code finished in no time. Assuming you've already got the database setup :)

Upvotes: 0

Related Questions