split text and insert into the column

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
fer0an
Forum Newbie
Posts: 12
Joined: Sat Jan 23, 2010 8:15 am

split text and insert into the column

Post by fer0an »

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
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: split text and insert into the column

Post by requinix »

Code: Select all

preg_split('/\s+/', $string)
will split a $string into parts separated by whitespace. Loop over that and run the INSERT query.
fer0an
Forum Newbie
Posts: 12
Joined: Sat Jan 23, 2010 8:15 am

Re: split text and insert into the column

Post by fer0an »

I used this code

Code: Select all

$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 below:
Fatal error: Call to a member function prepare() on a non-object in /home/...
any idea?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: split text and insert into the column

Post by requinix »

$db isn't an object.

How about posting the code to do with how $db is created?
fer0an
Forum Newbie
Posts: 12
Joined: Sat Jan 23, 2010 8:15 am

Re: split text and insert into the column

Post by fer0an »

I created it before :

Code: Select all

$db = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
$string = $title;
$words = explode(' ', $string);
 
$stmt = $db->prepare('INSERT INTO words (word) VALUES(?)');
 
foreach ($words as $word) {
   $stmt->execute(array($word));
 
it's working with one column and tested.
can you help me to use it with some other column?

thank you
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: split text and insert into the column

Post by requinix »

Did you overwrite $db anywhere? What does

Code: Select all

var_dump($db)
give?
fer0an
Forum Newbie
Posts: 12
Joined: Sat Jan 23, 2010 8:15 am

Re: split text and insert into the column

Post by fer0an »

no
Post Reply