Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.