Inserting array count into database

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
JohnHudson
Forum Newbie
Posts: 1
Joined: Mon Jul 05, 2010 7:18 am

Inserting array count into database

Post by JohnHudson »

Hi,

I have an issue that I am trying to figure out, but I'm not having much luck and wondered if anyone could give me some pointers (relative noob I'm afraid).

I have a string which I break down into separate words with the intention of inserting those words into a MySQL database along with a count of the number of times the word is used. For instance,

Code: Select all

$string = "This is a string containing these words. Some of these words need to be added to the database";
I've figured out how to convert the string to lowercase, remove punctuation, remove certain 'common' words ('this', 'is', 'a', 'to', 'of' etc) and then add each remaining word to an array so my result is as follows:

Code: Select all

$result = Array
(
    [0] => string
    [1] => containing
    [2] => these
    [3] => words
    [4] => some
    [5] => these
    [6] => words
    [7] => need
    [8] => added
    [9] => database
)
I also need words that are duplicated to be recognised in the database, so what the database would actually look like is this:

Word - Count
string - 1
containing - 1
these - 2
words - 2
need - 1
added - 1
database - 1

I understand I can get a word count by using array_count_values($result), but I've no idea how I would go about inserting that kind of data into a MySQL database, using an INSERT statement.

Any pointer in the right direction would be very much appreciated.

Many thanks,

JohnHudson
User avatar
Jade
Forum Regular
Posts: 908
Joined: Sun Dec 29, 2002 5:40 pm
Location: VA

Re: Inserting array count into database

Post by Jade »

First you'd need to create a table wordCount with with two fields, one field for the word and the other field for the number of times the word appears.

Then your code would be something along the lines of:

Code: Select all

<?php
//connect to your database up here first

$result; //this would be your array of the words
$count; //this would be be an array with the number of times each word appears in the string

//loop through your word array and insert the word/count for each result
for ($i = 0; $i < sizeof($result); $i++)
{
            mysql_query("INSERT INTO wordCount (theWord, totalCount) VALUES ('" . $result[$i] . "', '" . $count[$i] . "')")
            or die (mysql_error());
}
?>
Post Reply