I have tb words in a database :
=====================
= id = kata = posisi
=====================
= 1 = you = 1 =
= 2 = should= 2 =
= 3 = eat = 3 9 20 =
etc
Column posisi shows the positions of words in a sentence, that can be has 2 or more position for every word that I separated their position with space in its coloumn. The table comes from indexing process for sentence :
You should eat two bananas before lunch and eat two before your dinner and then consume one banana. i eat banana
I wanna get 5 words before and 5 next words from a keyword.
for example I submit keyword and I will get result :
eat two bananas before lunch and eat two before your dinner
and
eat two before your dinner and then consume one banana. i
here's the code I've tried :
require_once 'connection.php';
function getPosition ($keyword) {
$key = strtolower($keyword);
$query = mysql_query("SELECT * FROM words WHERE kata = '$key' ") or die(mysql_error());
while ($row = mysql_fetch_array($query)) {
$position = $row['posisi'];
}
return $position;
}
$key= 'And';
$and = getPosition($key);
$explode = explode (' ', $and);
foreach ($explode as $data => $datas){
for ($i = 1 ; $i < 6 ;$i++){
$nextdata[$i] = (int)$datas + $i;
$databefore[$i] = (int)$datas - $i;
$queryNext = mysql_query("SELECT kata FROM words WHERE posisi = '$nextdata[$i]' and posisi =$databefore[$i] ") or die(mysql_error());
while ($row = mysql_fetch_array($queryNext)) {
$position = $row['kata'];
}
//print_r($position);
}
}
But it doesn't work, maybe the problem is when it meet the column with has many position, it can't be read it. Please help me. Thank You :)
Related
So, I tried to create an algorithm(?) to assign a person to a classroom. The requirement for each class is :
Have at least 30 people and maximum of 45
The person name will not be "Homogen" (e.g: class 1 - 3 has all person name started with the letter "A", while class 4-5 the letter "B" etc.)
The gender is also evenly distributed
If the class is full, the remaining person will be moved to waiting list
My data has the column Unique ID, Name, and Gender. I'm still new to this kind of stuff (Algorithm?) so I don't even know where to start. Is it even possible? Where do I start? I am using PHP and my data is in MySQL Database
Step 1
You need to get data from DateBase (all people)
$host = '***';
$user = '***'';
$password = '***'';
$database = '***'';
$link = mysqli_connect($host, $user, $password, $database) or die("Error" . mysqli_error($link));
$query = "SELECT * FROM people";
$people = mysqli_query($link, $query) or die("Error" . mysqli_error($link));
mysqli_close($link);
Step 2
Conver mysql_result to Array and shuffle it.
$people = [];
foreach ($result as $person) {
$people[] = $person;
}
shuffle($people);
Step 3
There is algorithm:
$count = count($people);
// Classes
$classes = [];
const MIN_SIZE = 30;
const MAX_SIZE = 45;
$maxSizeClass= $count / MIN_SIZE;
$minSizeClass= $count / MAX_SIZE;
$countClasses = max(ceil($minSizeClass), floor($maxSizeClass));
$currentCountClass = $count / $countClasses;
$tmpClass = [];
foreach ($people as $person) {
if (count($tmpClass) < $currentCountClass) {
$tmpClass[] = $person;
} else {
$classes[] = $tmpClass;
$tmpClass = [];
}
}
if (count($tmpClass) >= MIN_SIZE) {
$classes[] = $tmpClass;
$tmpClass = [];
}
foreach ($tmpClass as $index => $person) {
foreach ($classes as &$class) {
if (count($class) < MAX_SIZE) {
$class[] = $person;
// be careful, PHP7 is OK
unset($tmpClass[$index]);
continue 2;
}
}
}
// persons awaiting distribution
$waitingQueue = $tmpClass;
Step 4
Result is:
$waitingQueue - persons awaiting distribution
$classes - classes with persons
$letters = array('a','b',....,'y','z');
foreach($letters as $letter){
$sql['male'] = "SELECT * FROM people_table WHERE person_name LIKE '".$letter."%' AND person_gender = 'male' ORDER BY person_name";
$sql['female'] = "SELECT * FROM people_table WHERE person_name LIKE '".$letter."%' AND person_gender = 'female' ORDER BY person_name";
foreach($sql as $key => $query){
$results[$key] = $connection->query($query);
for($i = 0; $i < $results[$key]->num_rows; $i++){
$people[$letter][$key][] = results->fetch_array(MYSQLI_ASSOC);
}
}
}
Here we have the lists of people listed by gender by letter... Now we can loop it and insert a man and a woman by pairs. If the count(); of the list of pairs is lesser than 30, people wait more. If bigger than 44 (because in pair isn't possible to have 45 people, if I don't missunderstand the question, of course) then save this 44 in a class array $class[$letter] which you can see all classes by each letter. To know about how many classes you have in total, you can use count($class); or if you would like to know how many classes of a specific letter you can do count($class[$letter]);.
You can redo other foreach in the $letters array or just put the loop inside the foreachabove to create the array of classes.
Inside the foreach($letters as $letter){} at the final:
if( !(count($people[$letter][$key]) < 15 OR count($people[$letter][$key]) < 15) ){
$she = count($people[$letter]['female'];
$he = count($people[$letter]['male'];
if($she < $he){
for($i = 0; $i < 2*count($she); $i++){
$class[$letter][$i] = $people[$letter]['female'][$i];
$class[$letter][$i+1] = $people[$letter]['male'][$i];
$i++;//Important to avoid replace values!
}
} else {
for($i = 0; $i < 2*count($he); $i++){
$class[$letter][$i] = $people[$letter]['female'][$i];
$class[$letter][$i+1] = $people[$letter]['male'][$i];
$i++;//Important to avoid replace values!
}
}
A false boolean in the bigger if means cannot create a class with this letter gender evenly distributed. You can loop again to make each class in an entry of an array.
I would like to select those movies which have similar titles.
I found this, but this way it dosn't work, it gives nothing. I would like to give toy story 2, toy story 3 and others with similar title like toy soldielrs, etc.
$title = "Toy Story";
$query = mysql_query("SELECT title, year, poster, LEVENSHTEIN_RATIO( ".$title.", title ) as textDiff FROM movies HAVING textDiff > 60");
I can compare strings in PHP with this function:
static public function string_compare($str_a, $str_b)
{
$length = strlen($str_a);
$length_b = strlen($str_b);
$i = 0;
$segmentcount = 0;
$segmentsinfo = array();
$segment = '';
while ($i < $length)
{
$char = substr($str_a, $i, 1);
if (strpos($str_b, $char) !== FALSE)
{
$segment = $segment.$char;
if (strpos($str_b, $segment) !== FALSE)
{
$segmentpos_a = $i - strlen($segment) + 1;
$segmentpos_b = strpos($str_b, $segment);
$positiondiff = abs($segmentpos_a - $segmentpos_b);
$posfactor = ($length - $positiondiff) / $length_b;
$lengthfactor = strlen($segment)/$length;
$segmentsinfo[$segmentcount] = array( 'segment' => $segment, 'score' => ($posfactor * $lengthfactor));
}
else
{
$segment = '';
$i--;
$segmentcount++;
}
}
else
{
$segment = '';
$segmentcount++;
}
$i++;
}
// PHP 5.3 lambda in array_map
$totalscore = array_sum(array_map(function($v) { return $v['score']; }, $segmentsinfo));
return $totalscore;
}
But how can I compare in a SELECT query or any other way?
You can use like queries for that:
Following example will return all the records from table customer for which customer name ends with kh
select * from customer where name like '%kh'
Following example will return all the records from table customer for which customer name start with kh
select * from customer where name like 'kh%'
Following example will return all the records from table customer for which the middle world of customer name is kh
select * from customer where name like 'kh%'
if you want more specific record then add some and/or condition in your query
I recommend you to read this
http://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html#operator_like
I think you might need to define how similar things need to be to be considered a match.
But if you just wanna search for containing words, you could split your search string by whitespaces and use it in a REGEXP in your query
$search_array = explode(" ", "Toy story");
$query = "SELECT title, year, poster FROM movies WHERE title REGEXP '".implode("|", $search_array)."'";
This would probably match a lot rows, but you could make a more restrictive regular expression.
I'm trying to make this works. I want to replace some parts of a sentence between given positions and then show the full sentence with the changes. With the following code, I'm able to make the changes but I don't know how to put together the rest of the sentence.
I have two arrays, one with the positions where a woman name appears and another one with men names. The code replaces the pronoun "his" by "her" when a woman is before a man between the intervals. The last thing I need is to reconstruct the sentence with the changes made but I don't know how to extract the rest of the sentence (the result, in the example, is from positions 0 to 20 (Maria her dress but) and 36 to 51 (Lorena her dog) but I need to extract from 20 to 36 (Peter his jeans) and 51 to the end (Juan his car) to merge them in their positions).
The result should be: "Maria her dress but Peter his jeans Lorena her dog Juan his car". I'll appreciate any help with this, I've been looking for other similar questions but I found nothing.
<?php
$womenpos = array("0","36"); //these arrays are just examples of positions
$menpos = array("20","51"); //they will change depending on the sentence
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
echo $sentence."\n";
foreach ($womenpos as $index => $value) {
$value2 = $menpos[$index];
if($value < $value2) {
echo "\nWoman(" . $value . ") is before man(" . $value2 . ")\n";
$end = ($value2 - $value);
$improved = str_replace(' his ', ' her ',
substr($sentence, $value, $end));
echo $improved."\n";
} else {
$improved = "Nothing changed";
echo $improved;
}
}
Ok, how about this:
$womenpos = array("0","36");
$menpos = array("20","51");
$bothpos = array_merge($womenpos,$menpos);
sort ($bothpos);
print_r($bothpos);
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
echo $sentence."\n";
for ($i = 0; $i<sizeof($bothpos); $i++) {
$start = $bothpos[$i];
if ($i ==sizeof($bothpos)-1) {
$end = strlen($sentence);
}
else {
$end = $bothpos[$i+1];
}
$length = $end-$start;
$segment = substr($sentence, $start, $length);
if (in_array($start, $womenpos)) {
$new_segment = str_replace (' his ', ' her ', $segment);
}
else { $new_segment = $segment; }
$improved .= $new_segment;
print "<li>$start-$end: $segment : $new_segment </li>\n";
}
print "<p>Improved: $improved</p>";
This combines the men's and women's position arrays to consider each stretch of text as one that might have an error. If that stretch of text starts at one of the womenpos points, then it changes 'his' to 'her'. If not it leaves it alone.
Does this get you in the direction you want to go in? I hope so!
This approaches the problem differently, but I wonder if it would provide the solution you're looking for:
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
$women = array ("Maria", "Lorena");
$words = explode (" ", $sentence);
for ($i=0; $i< sizeof($words); $i++) {
if ($words[$i] == "his" && in_array($words[$i-1], $women)) {
$words[$i] = "her";
}
}
print (join(" ", $words));
This goes through the words one at a time; if the preceding word is in the $women array and the current word is "his", it changes the word to "her". Then it spits out all the words in order.
Does this do what you need, or do you really want a complex string positioning answer?
I have this for loop that generates 10 results:
<?php
include "dbconnect.php";
$table = "SELECT id FROM players ORDER BY RAND()* ( 1 / percentage)";
for ($i = 0; $i < 10; $i++){
$result[0] = mysql_fetch_array(mysql_query($table));
foreach ($result as $winner){
echo $winner[0] . " ";
}
}
?>
It generates a result like:
10 10 11 9 13 11 10 12 8 12
My question is how do I count the generation? For the above example it would be:
8's = 1, 9's = 1, 10's = 3, 11's = 2, 12's = 2, 13's = 1.
I basically want to count the amount of specific results generated. Sorry if i'm not making much sense.
You need to get off of MySQL functions and check out PDO or MySQLI at a minimum. But for the meat of the question:
Don't run a query, full or limited in the loop
Look at the LIMIT clause in the query
array_count_values will count the values. You can loop it and echo or whatever
Example:
$table = "SELECT id FROM players ORDER BY RAND()*(1/percentage) LIMIT 10";
$result = mysql_query($table);
while($row = mysql_fetch_array($result)) {
$winner[] = $row[0];
}
echo implode(' ', $winner);
foreach(array_count_values($winner) as $number => $count) {
$output = "$number's = $count";
}
echo implode(', ', $output);
You're existing code to make the random choice work would look like (LIMIT 1):
$table = "SELECT id FROM players ORDER BY RAND()*(1/percentage) LIMIT 1";
for($i = 0; $i < 10; $i++){
$result = mysql_fetch_array(mysql_query($table));
$winner[] = $row[0];
}
echo implode(' ', $winner);
if you check the php manual:
http://php.net/manual/en/function.mysql-query.php
then try something like this:
while ($row = mysql_fetch_assoc($table)) {
echo $row['column_name'];
echo $row['column_name'];
//.. you get the idea
}
The id is usually the first column in a database table. This is why you are just getting the id. You need to access each row in the same way you access arrays.
I should point out that the mysql library is deprecated. So you should consider using something like PDO instead.
Im trying to loop through a mysql table and check if a row contains the number I specify:
Here is what I have:
mysql table with numbers:
mysql table:
no1|no2|no3|no4|no5
1 3 5 2 6
4 7 8 9 8
2 6 9 1 0
...
For Example: I have number
4 5 3 7
So in the first row i should get a total of 2 as there are numbers 3 and 5 first row and this numbers are in the number I have specified.
In the second row I should get a total of 1 as only a 4 is in the row and the number i have specified.
And in the last row total should be 0 as there are no matches.
I hope its clear.
I have tried the following but it dont work I hope someone can help me work it out thanks in advance.
$lottono1=4;
$lottono2=5;
$lottono3=3;
$lottono4=7;
$no1 = 0;
$no2 = 0;
$no3 = 0;
$no4 = 0;
do { ?>
// i done the following if code for each numbers but
//putting this only to take less space
if (($row_Recordset1['no1']=$lottono1) || ($row_Recordset1['no1']=$lottono2) || ($row_Recordset1['no1']=$lottono3) || ($row_Recordset1['no1']=$lottono4)) {
$no1=1;
}
while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
select *,
if(no1 in (4,5,3,7),1,0)+
if(no2 in (4,5,3,7),1,0)+
if(no3 in (4,5,3,7),1,0)+
if(no4 in (4,5,3,7),1,0)+
if(no5 in (4,5,3,7),1,0) as found
from table
Well for one, your operators are wrong in your "if" conditions (you're setting rather than comparing).
Regardless i'd do something more like:
$numbers_to_match = array(4,5,3,7) ;
$query = mysql_query("select * from `table` where ____",connection_here);
$matches[] = array();
$i=0;
while($r=mysql_fetch_array($query)){
$matches[$i]=0;
foreach($r as $val){
if (in_array($val,$numbers_to_match)){
$matches[$i]++;
}
}
$i++;
}
print_r($matches);
Untested, but this should give you an array that lists the number of matches for each row
To accomplish with PHP/MySQL you can do the following:
$query = 'SELECT * FROM table';
$result = mysql_query($query) or die();
$matchValues = array(4,5,3,7);
while($row = mysql_fetch_array($result)){
$counter = 0;
foreach($matchValues as $value)
{
if(in_array($value, $row))
{
$counter++;
}
}
print "Searched row and found $counter matches<br/>";
}