0

I am using MySQL. I have a table called entries. This table has a column called body. The body column has string data (about 500 words long).

Now, I want transfer above body column into column_1,column_2,.... column_300 which contains nth word in each body column. So, if body column has a data like "I ate a lunch today", then column_1 would have 'I' , column_2 would have 'ate', and so on. I guess I can work this in PHP, but I have been wondering if it is possible in query in MySQL.

user482594
  • 16,878
  • 21
  • 72
  • 108

2 Answers2

2

See: Split value from one field to two

Community
  • 1
  • 1
entropo
  • 2,481
  • 15
  • 15
0

Here you have a php solution.

<?php
  //Connect to mysql server
  $cn = mysql_pconnect("server", "username", "password");
  mysql_select_db("database_name");
  $rs = mysql_query("SELECT id, body FROM entries", $cn);  

  //Traverse each entry row      
  while($row = mysql_fetch_array($rs)){
     list($id, $body) = $row;
     $words = explode(" ", $body); //split by spaces (can be improved)
     $sqlUpdate = "UPDATE entries SET ";
     $sets = array();
     //Traverse words
     for($i=1; i<=count($words); $i++){
        $word_for_mysql = mysql_escape_string($words[$i-1]); //$i-1 cause arrays are zero-based index
        $sets[] = "column_$i = '$word_for_mysql'"; //i.e: column_1 = 'lorem'
     }
     $sqlUpdate.= join(", ", $sets)." WHERE id='$id'";     
     mysql_query($sqlUpdate, $cn);
  }
?>

Anyway, I wonder why you want to do this

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61