fer0an Posted January 24, 2010 Share Posted January 24, 2010 hello anyone can help me about: splitting a text with space between them , then insert each one to db? for example : $text = My name is David I want it divided to: $text1 = my; $text2 = name; $text3 = is; $text4 = David ; then insert $text1 into db; then insert $text2 into db; then insert $text3 into db; then insert $text4 into db; thank you Quote Link to comment https://forums.phpfreaks.com/topic/189610-split-text-and-insert-into-the-column/ Share on other sites More sharing options...
Daniel0 Posted January 24, 2010 Share Posted January 24, 2010 Untested. <?php $db = new PDO('mysql:host=localhost;dbname=test', 'user', 'password'); $string = 'my name is David'; $words = explode(' ', $string); $stmt = $db->prepare('INSERT INTO words (word) VALUES(?)'); foreach ($words as $word) { $stmt->execute(array($word)); } Or using PHP 5.3 and anonymous functions (still untested): <?php $db = new PDO('mysql:host=localhost;dbname=test', 'user', 'password'); $string = 'my name is David'; $stmt = $db->prepare('INSERT INTO words (word) VALUES(?)'); array_walk(function($word) use ($stmt) { $stmt->execute(array($word)); }, explode(' ', $string)); Quote Link to comment https://forums.phpfreaks.com/topic/189610-split-text-and-insert-into-the-column/#findComment-1000756 Share on other sites More sharing options...
fer0an Posted January 24, 2010 Author Share Posted January 24, 2010 thank you for code, it's working but I've another problem my table has `id`, `name`, `description`, `weight`, `hits`, `created` column and I want insert this splited word to description. I used $string = $title; $words = explode(' ', $string); $stmt = $db->prepare("INSERT INTO tag_term (`id`, `name`, `description`, `weight`, `hits`, `created`) VALUES (NULL ,?, '".$title."' , '0', '0', '".date('Y-m-d G:i:s')."')"); foreach ($words as $word) { $stmt->execute(array($word)); but I recived an error (Fatal error: Call to a member function prepare() on a non-object in /home/...) please help me. Quote Link to comment https://forums.phpfreaks.com/topic/189610-split-text-and-insert-into-the-column/#findComment-1000760 Share on other sites More sharing options...
fer0an Posted January 24, 2010 Author Share Posted January 24, 2010 anyone can answer? Quote Link to comment https://forums.phpfreaks.com/topic/189610-split-text-and-insert-into-the-column/#findComment-1000863 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.