Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How do I insert this into the database?

I have this file:

[player_id] => 70658
[mobile_number] => 09********
[name] => gorbani
[password] => ******
[verification_code] => KUTY6U
[subscription] => 0
[gold] => 147350
[date_joined] => 2011-04-26 20:02:40
[free_spin] => 0
[player_status] => 1
[scriptedSpin] => PLG
[message_flag] => N
[gold_award] => 0

Thats just 1 entry out of 300,000 or more in one text file. I need to automatically, insert the ff. into a mysql db where only the

mobile_number
name
password
gold

will be taken and inserted.

Thank you.

Regards, Mehihi

That is how the file is being formatted:

[player_id] => 70658
[mobile_number] => 09********
[name] => gorbani
[password] => ******
[verification_code] => KUTY6U
[subscription] => 0
[gold] => 147350
[date_joined] => 2011-04-26 20:02:40
[free_spin] => 0
[player_status] => 1
[scriptedSpin] => PLG
[message_flag] => N
[gold_award] => 0

[player_id] => 70659
[mobile_number] => 09********
[name] => gorbani2
[password] => ******
[verification_code] => 22222
[subscription] => 0
[gold] => 147350
[date_joined] => 2011-04-26 20:02:40
[free_spin] => 0
[player_status] => 1
[scriptedSpin] => PLG
[message_flag] => N
[gold_award] => 0

and so on..

I have tried this but no good:

$sql = array(); 
foreach( $myarray as $row ) {
$sql[] = '('.$row['ID'].', "'.mysql_real_escape_string($row['NAME']).'","'.$row['PRICE'].'")';}
mysql_real_query('INSERT INTO table (ID, NAME,PRICE) VALUES '.implode(',', $sql));
share|improve this question
1  
What have you tried? –  abhshkdz Oct 25 '12 at 14:01
    
    
That's exactly how the file contents looks like? Any kind of separator between the records or just "each chunk of 13 lines is one record, happy parsing"? –  VolkerK Oct 25 '12 at 14:03
    
edited my post. thanks. –  user1553142 Oct 25 '12 at 14:06

1 Answer 1

When you will have your associative array do the following:

First prepare a SQL query.

$sql = "INSERT INTO ".$table." ("; 
for ($i=0; $i<count($arr); $i++)
{ 
  $sql .= key($arr); 
  if ($i < (count($arr)-1))
  { 
    $sql .= ", "; 
  } else $sql .= ") "; 
  next($arr); 
} 
reset($arr); 
$sql .= "VALUES ("; 
for ($j=0; $j<count($arr); $j++)
{ 
  $sql .= "'".current($arr)."'"; 
  if ($j < (count($arr)-1))
  { 
    $sql .= ", "; 
  } else $sql .= ") "; 
  next($arr); 
}

Now, since you have your SQL query stored in $sql you just execute a query in your preffered method.

Note: mysql_query is depricated, you should use PDO or something else instead.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.