Jump to content

split text and insert into the column


fer0an

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/189610-split-text-and-insert-into-the-column/
Share on other sites

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));

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.