I was wondering if some one enters a word into a database from a php form how can you count how many people have entered that same word in the database as well as how not to create a whole unique id for that same word just a count for that same word when the user enters the same word.
Are people entering single words only? Like, you've got a form, and I go there and type in "toast" and hit enter?
something like this should work, assuming your words
table has word
as a string and count
as an integer. u may need to modify it depending on how u are interacting with mysql
$word = mysql_real_escape_string($_POST['word']);
$query = 'UPDATE words SET count = count+1 WHERE word = '.$word;
mysql_query($query);
if( !mysql_affected_rows() ) {
$query = 'INSERT INTO words (word,count) VALUES('.$word.',1)';
mysql_query($query);
}
I am not really sure what you are trying to do, but here are some approaches. Lets assume you've got a table like:
| User | Word | --------------- | xyz | hello|
You could get the count by executing the following MySQL-Query:
SELECT count(*) FROM table WHERE Word = 'hello' GROUP BY Word;
On the other hand, if you had:
| Word | Count | ---------------- | hello| 123 |
You'd just have to check if a word already exists. If not, you insert it, otherwise, you increment it like that:
UPDATE table SET Count += 1 WHERE Word = 'hello';
Best Regards,
x3ro
You can create the table wordsCount with the following schema.
id | word | count
------------------
1 | word1 | 15
2 | word2 | 8
etc.
When someone types the word you can check if the word is already in the table and insert ot update counter. In MySQL can use INSERT ... ON DUPLICATE KEY UPDATE. Like this:
INSERT INTO table (word,count) VALUES ('word3',1)
ON DUPLICATE KEY UPDATE count=count+1;
It is better than checking if word exists using
SELECT * FROM table WHERE word = 'word3'
and then deciding if to use INSERT or UPDATE. Of course you have to put UNIQUE KEY on the word column.
The following query will return a result set displaying the number of occurences of each value in the "Value" column of the "Data" table. Add a "WHERE" clause if you're only interested in one particular "Value".
SELECT Value, COUNT( DISTINCT Id ) AS Occurrences
FROM Data
GROUP BY Value