Link to home
Start Free TrialLog in
Avatar of kbios
kbios

asked on

How do I insert multiple records in a php mysql db?

I have data stored in localStorage variables. I want to retreive the data and pass to an INSERT INTO statement and then have mysql process the statement. The VALUES will be parsed from the localStorage variable. Any tips or ideas for a better approach would be appreciated.

Please look at the code below:

<?php
    $conn = mysql_connect("localhost", "X", "Y.") or die(mysql_error());
                mysql_select_db("test");
            
      for ($i=1;$i<=parseInt(localStorage.trxCtr);i++)
      {      
           if ( localStorage["item" + i] != "X" )
           {                        
           $sql = "INSERT INTO table (field1, field2, field3) VALUES ('data1', 'data2', 'data3')";
           $result = mysql_query($sql, $conn) or die(mysql_error());
           }  
       }
 
    mysql_close($conn);
?>
Avatar of themrrobert
themrrobert
Flag of United States of America image

This way is superior in my opinion
foreach(localStorage as $key => $value)
//key is itemi and value is value
  if($val != "X") {
    $sql = "INSERT INTO table (....)";
    $result = mysql_query($sql,$conn) or die(mysql_error());
  }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of themrrobert
themrrobert
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
What exactly are you doing on the fields? I often use the $key in the query and other places, so with the limited information you've provided, this is realistically the best answer possible, iterating through each identifier, without worrying about ones that might not exist (because it only iterates EXISTING items in the array.)

If you need anything else regarding this question, please post. Otherwise please accept my answer :-)

-Robert
Avatar of kbios
kbios

ASKER

I think I can gleen what I need from your code. It at least gives me some direction. Thanks.