1

I have one string, it is given below,

$str = '1, test1, 22, 2, test2, 44, 3, test4, 55, 4, test7, 12...';  

The string contains id, name, age, I have to insert into database like this,

 id | name | age  
  1 | test1| 22    
  2 | test2| 44  

Please let me know, How can I achieve this one?

Thanks In advance

2
  • What you gave is a string.. Commented May 23, 2014 at 7:01
  • @Ugly Eddie...it is string Commented May 23, 2014 at 7:03

2 Answers 2

3

You can do something like....

$str = '1, test1, 22, 2, test2, 44, 3, test4, 55, 4, test7, 12';  
$array = explode(", ",$str);
$result_array = array_chunk($array, 3);

I guess you can take ahead from this to insert that into your db.

DEMO.

Sign up to request clarification or add additional context in comments.

3 Comments

@Rikesh..this will work..but if the string length is 100000, then we have to write too many queries for this..Is there any other method, so that we can insert it in one query?
You can create a single query too.
@Rikesh..How can I acheive this one?..can you give any demo??
0

Alternatively, you can just build a multi insert query on this one. Consider this example:

$str = '1, test1, 22, 2, test2, 44, 3, test4, 55, 4, test7, 12';
$str = explode(',', $str);
$str = array_map('trim', $str);
$data = array_chunk($str, 3);
$values = array();
foreach($data as $key => $value) {
    $values[] = '("'.implode('", "', $value).'")';
}
$statement = "INSERT INTO `table` (column1, column2, column3) VALUES ". implode(',', $values);

// this produces:
// INSERT INTO `table` (column1, column2, column3) VALUES ("1", "test1", "22"),("2", "test2", "44"),("3", "test4", "55"),("4", "test7", "12")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.