mysql count occurrences of special character in a field - php

I am wanting to count all occurrences of the # symbol in a field and originally i thought LIKE '%#%' would be the way to go, but if the character appears in the field more than once it only counts it as one.
What other method are there that i could use that would count every occurrence?
Thanks.
EDIT
For anyone needing it, this is what i ended up using that works.
$count = 0;
$sql = mysql_query("SELECT LENGTH(field_name) - LENGTH(REPLACE(field_name,'#','')) AS 'occurs' FROM table_name WHERE field_name LIKE '%#%'");
while ($data = mysql_fetch_assoc($sql)) {
$count += $data['occurs'];
}
echo $count;

select length('aa:bb:cc:dd')-length(replace('aa:bb:cc:dd',':',''));
source: http://lists.mysql.com/mysql/215049

You could make this even simpler by using the ``substr_count function in php. see below.
$message = $row['themessage'];
echo substr_count($message, '#');
what this will return is the number of times # has occurred in your "themessage" field in your database.

Related

autoincrement alphanumeric in phpmyadmin mysqlserver

i want to autoincrement the alphanumeric characters
Ex:amp001,amp002,amp003
Can anyone plz help me in solving this problem.
i should get column like
id
abc001
abc002
abc003
abc004
..
..
..
You can't auto increment alphanumeric values. Just Change the field type to numeric and set auto increment to that field. Concate your string value before the ID, while fetching the value. Eg: <?php echo "abc".$row['id']; ?>
If you really want this, use php's uniqid function.
Look this example
//connect to you database
//$count = mysql_query("select count(*) from table_name");
$id = "abc";
if (strlen($count+1) < 4)
{
$count++;
for($i=0;$i<(3 - strlen($count));$i++)
{
$id .='0';
}
$id .= $count;
}

Get Popular words in PHP+MySQL

How do I go about getting the most popular words from multiple content tables in PHP/MySQL.
For example, I have a table forum_post with forum post; this contains a subject and content.
Besides these I have multiple other tables with different fields which could also contain content to be analysed.
I would probably myself go fetch all the content, strip (possible) html explode the string on spaces. remove quotes and comma's etc. and just count the words which are not common by saving an array whilst running through all the words.
My main question is if someone knows of a method which might be easier or faster.
I couldn't seem to find any helpful answers about this it might be the wrong search patterns.
Somebody's already done it.
The magic you're looking for is a php function called str_word_count().
In my example code below, if you get a lot of extraneous words from this you'll need to write custom stripping to remove them. Additionally you'll want to strip all of the html tags from the words and other characters as well.
I use something similar to this for keyword generation (obviously that code is proprietary). In short we're taking provided text, we're checking the word frequency and if the words come up in order we're sorting them in an array based on priority. So the most frequent words will be first in the output. We're not counting words that only occur once.
<?php
$text = "your text.";
//Setup the array for storing word counts
$freqData = array();
foreach( str_word_count( $text, 1 ) as $words ){
// For each word found in the frequency table, increment its value by one
array_key_exists( $words, $freqData ) ? $freqData[ $words ]++ : $freqData[ $words ] = 1;
}
$list = '';
arsort($freqData);
foreach ($freqData as $word=>$count){
if ($count > 2){
$list .= "$word ";
}
}
if (empty($list)){
$list = "Not enough duplicate words for popularity contest.";
}
echo $list;
?>
I see you've accepted an answer, but I want to give you an alternative that might be more flexible in a sense: (Decide for yourself :-)) I've not tested the code, but I think you get the picture. $dbh is a PDO connection object. It's then up to you what you want to do with the resulting $words array.
<?php
$words = array();
$tableName = 'party'; //The name of the table
countWordsFromTable($words, $tableName)
$tableName = 'party2'; //The name of the table
countWordsFromTable($words, $tableName)
//Example output array:
/*
$words['word'][0] = 'happy'; //Happy from table party
$words['wordcount'][0] = 5;
$words['word'][1] = 'bulldog'; //Bulldog from table party2
$words['wordcount'][1] = 15;
$words['word'][2] = 'pokerface'; //Pokerface from table party2
$words['wordcount'][2] = 2;
*/
$maxValues = array_keys($words, max($words)); //Get all keys with indexes of max values of $words-array
$popularIndex = $maxValues[0]; //Get only one value...
$mostPopularWord = $words[$popularIndex];
function countWordsFromTable(&$words, $tableName) {
//Get all fields from specific table
$q = $dbh->prepare("DESCRIBE :tableName");
$q->execute(array(':tableName' = > $tableName));
$tableFields = $q->fetchAll(PDO::FETCH_COLUMN);
//Go through all fields and store count of words and their content in array $words
foreach($tableFields as $dbCol) {
$wordCountQuery = "SELECT :dbCol as word, LENGTH(:dbCol) - LENGTH(REPLACE(:dbCol, ' ', ''))+1 AS wordcount FROM :tableName"; //Get count and the content of words from every column in db
$q = $dbh->prepare($wordCountQuery);
$q->execute(array(':dbCol' = > $dbCol));
$wrds = $q->fetchAll(PDO::FETCH_ASSOC);
//Add result to array $words
foreach($wrds as $w) {
$words['word'][] = $w['word'];
$words['wordcount'][] = $w['wordcount'];
}
}
}
?>

Running a statement based on information from POST variable

I'm in a bit of pickle but the answer is probably pretty simple.
So I have my POST variable:
Array ( [accept] => accept,29 [accept1] => accept,30 [submit] => Save Selections )
That's just a print_r of $_POST.
Basically what I want to do is get the first variable, remove the 'accept,' part and store the number next to it in a variable, run some MySQL queries using that variable (containing that number) then move onto the next one; removing the 'accept,' storing the number next to it and running a query using that stored number. It want to do this for as many times is necessary to go through all the elements containing 'accept,' then a number.
Any help would be appreciated.
I was playing around with some ideas and have this code. It obviously doesn't work but perhaps I could fix and build on it?
while($i <= $elements)
{
while($x == 1)
{
$id = explode(',', next($_POST));
echo $id;
$x = 0;
}
$i++;
}
Im not sure this would fix your problem but I hope this helps and gives you an idea:
$i = 0;
while($i <= count($your_array))
{
$your_var = substr($your_array[$i], 7, 2); //get the number from your accept,29
$query = "SELECT * FROM TABLE WHERE COLUMN = ". $your_var; //use it to run queries as you said
$i+=1;
}
UPDATE - Im not sure if this would work
foreach($your_post_array as $items)
{
$your_var = substr($items, 7, 2);
$query = "SELECT * FROM TABLE WHERE COLUMN = ". $your_var; //use it to run queries as you said
$i+=1;
}
Maybe you should try to echo first the variables to make sure echo $your_var = substr($items, 7, 2);
I would use a foreach loop to loop through $_POST, check if the key starts with accept (stripos?), explode the value if it does and get the second value of the found array and store that somewhere for later use.
By the way, if possible I would change the front-end so that you have just one variable (an array) in $_POST you have to loop through.

PHP need help to filter a loggfile

So my problem is this I got a code that loops trough a loggfile then compares them to a treestructure and then gives them a id that correspond to the id in the structure. To not get a lot of bad traffic i sort out all the 302 and above.
The problem is now that i want some specific 302s to count that have a particular pagetype in the structure. This is not a big problem as I can just match the url in the loggfile against the url in the tree structure but some loggfiles does not use friendly url while the structure is in friendly url this creates a problem but I can just match the id in the query parameter with the id in the structure. I then make a string of all the ids that match the special pagetype that I want.
The problem is this I can not get the Mysql statement to work, it looks like this.
$sqlQ1 = "SELECT `lid` FROM logfile WHERE date = '$date' AND ´query´ IN '$check'";
A example query can look like this "id=4&epslanguage=sv" so I want to check only the id=X part.
It´s a kinda easy question really im just stuck and can not get it to work, any help is appreciated!
I think your Q is: How do I extract id from that part of a line?
".. so I want to check only the id=X part."
Once you have isolated that string then you can use:
$string = "id=4&abclang=sv";
parse_str($string);
echo $id; // 4
EDIT
In light of other responses:
$strings[] = "id=4&abclang=sv";
$strings[] = "id=45&abclang=en";
$vals = array();
foreach( $strings as $string){
parse_str($string);
$vals[] = $id ;
}
$in_clause = join(",", $vals) ;
$sql = "SELECT lid FROM logfile WHERE something IN ($in_clause) ";
echo $sql; // SELECT lid FROM logfile WHERE something IN (4,45)
So you have the IDs already and want to filter the MySQL query to just get these rows?
$check = Array(1, 2, 3, 4);
$check = implode(",", $check);
$sqlQ1 = "SELECT `lid` FROM logfile WHERE date = '$date' AND ´query´ IN ($check)";

MySQL + PHP: How to do search and show summary rather than entire result

was wondering how to do a search result using PHP + MySQL but not show all the data in the result but only a SUMMARY (lets say limited to 200 characters). And the summary would exactly contain the keyword portion. So -100 characters+keyword+100 characters might be how it would be shown.
Thanks!
Assuming you are fine with taking the first instance of the keyword to use in your summary, you could break up the results of your query in PHP in a way similar to this:
$sql = "SELECT data_field FROM your_table WHERE data_field LIKE '%".$keyword."%'";
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)) {
$data = $row['data_field'];
$first_pos = strpos($data,$keyword);
if ($first_pos !== false) {
$output = substr($data,max(0,$first_pos - 100),200 + strlen($keyword));
echo $output;
}
}
Obviously you could do whatever suited your needs with $output once you had it.

Categories