With the updated code below, my search is working, but only using the last word in the Array. Is there a way to search the MySQL column using all words the user inputted?
Note: All input sanitization and escaping is completed in my code but not shown here.
I have two PHP arrays: $search_exploded (user inputted search terms) and $metaphoneArr (metaphones of keywords in MySQL).
I'm cycling through $search_exploded and $metaphoneArr, and if the Levenshtein is less than 2, then I'm adding the metaphone element to a third array called $levenResultsArr.
In MySQL, I'm joining two tables, and if there's a result in my third array ($levenResultsArr) that matches a row in my metaphone_col, then I want the results printed. Somehow, though, I am not referencing the third array correctly in the MySQL statement.
Any advice? Here is part of my PHP code.
$levenResultsArr = array();
foreach ($search_exploded as $search_each => $searchWord) {
$search_each2 = metaphone($searchWord);
echo $search_each2 . "<br/>";
foreach ($metaphoneArr as $metaword => $val) {
$lev = levenshtein($search_each2, $val);
if ($lev < 2) {
array_push($levenResultsArr, $search_each2);
}
}
}
// And shown below is the MySQL statement
$constructs = "
SELECT vt.idvideolist,
vt.videotitle,
vt.videodescription
FROM videolist_tbl vt
INNER JOIN keyword__video k2v ON (vt.idvideolist = k2v.video_id)
INNER JOIN keywords_tbl k ON (k2v.keyword_id = k.idkeywords_tbl)
WHERE k.metaphone_col = '$search_each2'
";
It's only searching using the last word in the array instead of all words in the array.
You're correct that you aren't referencing your array correctly in your query. You are simply referencing the variable '$search_each2'. You want to check the entire array. The best way to do this would to be to convert the array to a string using implode and using the MySQL IN clause. We need to modify the array first to format it correctly:
foreach($levenResultsArr as &$foo){
$foo = "'".$foo."'"; //add single quotes around each object in the array
}
$levenAsStr = implode(",", $levenResultsArr);
Then simply change your last line to the following:
WHERE k.metaphone_col IN (".$levenAsStr.")";
Did this from memory because I'm not in a testing environment, please let me know if there are any syntax errors. Should work for you!
Without seeing more of the code its a bit difficult to determine what is going on. A couple of thoughts though.
What var is the array containing all search terms?
I noticed you are pushing items into $levenResultsArr. I don't see it being used in the query though.
If it is $search_each_2 you may try using the IN syntax:
WHERE k.metaphone_col IN '$search_each2';
This will only match exact values however. i.e.:
some value does not return if the IN array contains value. The array would have to contain some value
If you need it to match partial searches you may try using LIKE with wildcards: %
WHERE k.metaphone_col LIKE "%searchTerm1%"
OR k.metaphone_col LIKE "%searchTerm2%"
OR k.metaphone_col LIKE "%searchTerm3%"
You could potentially use the implode function to create the sql string from the array: http://php.net/manual/en/function.implode.php
Related
I am trying to build a string made of the results from sql and I do not know how achieve this when the data from the db is bigger than 1.
I was able to do it when the result from the database is one.
$result = $stmt_grade->fetch(PDO::FETCH_ASSOC);
$str ="[{$result['score_access']}, {$result['score_training']},
{$result['score_expectation']}, {$result['score_total']} ]";
but when I needed to loop the fetch_assoc I was not able to assign a value to variables or directly build the string.
while ($resultcount = $stmt_count->fetch(PDO::FETCH_ASSOC)){
$resultcount['subarea'];
}
I have looked everywhere and did not find any solutions or any similar approach to find inspiration. I hope someone can help me. Thank you in advance!
The most obvious way to do this is loop through all of the responses in a while loop, and continually append to your string using the .= operator. You can tell when you run out of records because $result will be false.
I separated each record with a newline. It also looked like you wanted to count results, so I added that, too.
$str = ""; // start with an empty string
$count = 0;
while ( ($result = $stmt_grade->fetch(PDO::FETCH_ASSOC)) !== false ) {
// increment the record count
$count++;
// add a new line to the output string
$str .= "[{$result['score_access']}, {$result['score_training']},{$result['score_expectation']}, {$result['score_total']} ]\n";
}
That should do it.
All you need is to name your string properly.
And then use a proper way to create a JSON string. Which consists of two parts:
Create a array of desired structure. Or at least provide a that structure here to let us to provide you with the code.
Use json_encode().
Assuming you need a nested array like this
[[1,2,3],[1,2,3],[1,2,3]]
the code would be
$result = $stmt_grade->fetchAll(PDO::FETCH_NUM);
echo json_encode($result);
thanks for all the answers provided without you I could not made it. Finally, I achieved the desirable result as follow, probably it is not elegant but works:
$stmt_count= $user->countbyespeciality();
while ($resultcount = $stmt_count->fetch(PDO::FETCH_ASSOC)){
$prueba.= "{$resultcount['subarea']},";
$prueba2.= "{$resultcount['number']},";
}
$string=rtrim($prueba, ",");
$string2=rtrim($prueba2, ",");
$final="[{$string}]";
$final2="[{$string2}]";
The output is [something,something] [1,2,] as expected.
thanks again!
I'm not used to work with arrays, and now i have to, and i need some help guys.
I have a list of absences,that contain multiples values. They are all ids (like 4,25,100...) separed by a ','.
I want to add every single id in a table (insert query),i know the simple methode :
Insert into table (columns..) Values(values1,value2,...),
(values1,value2,...),
(values1,value2,...),
(values1,value2,...)
But i dont know how to use it the the serialsed array.
Explode the string on the commas, then iterate over the resulting array. Understanding arrays is essential to PHP (and coding in general), so check out http://php.net/manual/en/language.types.array.php.
$string = '4,25,100';
$array = explode(',', $string);
foreach ( $array as $value ) {
$sql = "INSERT INTO `table` (`some_column`) VALUES ('".$v."')";
}
I tried many time, but I still don't understand why the output is not a string, anything wrong ? help me check it. The final output should be a uppercase name string
<html>
<p>
<?php
// Create an array and push on the names
// of your closest family and friends
$name = array();
array_push($name,"Mike");
array_push($name,"Jane");
array_push($name,"Jack");
array_push($name,"Nike");
array_push($name,"Ash");
array_push($name,"Chris");
array_push($name,"Zark");
// Sort the list
sort($name);
join(",",$name);
// Randomly select a winner!
$random = count($name,rand(0,7));
// Print the winner's name in ALL CAPS
$winner = strtoupper($random);
print($winner);
?>
</p>
</html>
$random = count($name,rand(0,7));
This line assigns the count of elements in $name. I don't know what else you expected to get back other than a number here.
What you really want:
echo strtoupper($name[array_rand($name)]);
http://php.net/manual/en/function.array-rand.php
Other Notes:
Your call to join() doesn't do anything useful since you're not doing anything with the return value.
Your call to sort is pointless if you're just picking a random entry later.
Pick a plural name for your array names so you know they are arrays. $names instead of $name.
If you know all of the array elements ahead of time, no need for array_push(), just use an array literal: array('Mike', 'Jane', /* etc */)
If you're outputting data into the context of HTML, always use htmlspecialchars() to make sure any reserved characters are escaped properly. This isn't a problem with the code you literally have here, but will be as soon as you want to output < or ".
I'm querying a table in a db using php. one of the fields is a column called "rank" and has data like the following:
none
1-bronze
2-silver
3-gold
...
10-ambassador
11-president
I want to be able to sort the results based on that "rank" column. any results where the field is "none" get excluded, so those don't factor in. As you can already guess, right now the results are coming back like this:
1-bronze
10-ambassador
11-president
2-silver
3-gold
Of course, I would like for it to be sorted so it is like the following:
1-bronze
2-silver
3-gold
...
10-ambassador
11-president
Right now the query is being returned as an object. I've tried different sort options like natsort, sort, array_multisort but haven't got it to work the way I'm sure it can. I would prefer keeping the results in an object form if possible. I'm passing the data on to a view in the next step. although, it's perfectly acceptable to pass the object to the view and then do the work there. so it's not an issue after all. :)
thank you for your help. i'm hoping I'm making sense.
How about using this function to sort. I assume if you are getting an object you should convert object to array then use this
function arraySubSort($array, $subkey, $sort = 'asort')
{
foreach($array as $key => $value)
{
$temp[$key] = strtolower($value[$subkey]);
}
$sort($temp);
foreach($temp as $key => $value)
{
$result[] = $array[$key];
}
return $result;
}
$data = $your_array;
$field = 'ranks';
arraySubSort($data,$field);
It will sort the array with the field you assign. If you are getting multiple records its a good thing to use to sort.
Get the values in an array an sort it in PHP using natsort()
Natsort
This will work -
SELECT alphanumeric, integer FROM sorting_test ORDER BY LENGTH(alphanumeric), alphanumeric
source - Natural Sort in MySQL
I have the following function.
return $this->_blockPhoto ( $selected_screenshots, $this->aDataEntry['author_id']);
It requires that the variable $selected_screenshots is an array of values.
The problem is that I have to take the values from a mySQL look, that is reported below.
If there is only one value, everything works fine. But when there are more values in the DB, I cannot put all those values into the variable array.
In fact, since return $this->_blockPhoto ( $selected_screenshots, $this->aDataEntry['author_id']); is outside the mySQL loop, it gets only the first value of the loop.
So how do I store all the values from the mySQL loop into the variable? And not only the first value?
I tried to manually assign the array to the variable in the loop $selected_screenshots = array($qryrow1['media_id']); but it does not work and I do not think it has any sense :)
$qry1="SELECT * FROM modzzz_articles_screenshots WHERE media_id='".$selected_screenshots_ID."' AND entry_id='".$this->aDataEntry['id']."'";
$qryr1=mysql_query($qry1) or die("Error selecting: ".mysql_error());
while($qryrow1 = mysql_fetch_array($qryr1)) {
$selected_screenshots = array($qryrow1['media_id']);
} // END OF THE LOOK
return $this->_blockPhoto ( $selected_screenshots, $this->aDataEntry['author_id']);
Can anyone give me the solution, with code? I am really confused.
Thanks
Your code keeps overwriting $selected_screenshots with a new array each time. Instead, you want to append it:
$selected_screenshots = array();
while ($qryrow1 = mysql_fetch_array($qryr1)) {
$selected_screenshots[] = $qryrow1['media_id'];
}
You can save all the mysql values by looping through your results and appending them to the end of $selected_screenshots to do this please look below. Right now you are just assigning $selected_screenshots one value and neglecting the other values, so $selected_screenshots is having the last value that mysql returns.
This is covered http://php.net/manual/en/language.types.array.php under the heading 'Creating/modifying with square bracket syntax'