Simple Search Engine Only Works With One SQL Row - php

I'm making a rather simple search engine with PHP and I've ran into a problem... The engine will only work for one SQL row. In the table the PHP is connected to, there are two rows. One named "The Painful Truth" and the other "Darkness Rising". If you type "darkness" or "rising" into the search bar it will come back with "Darkness Rising" as expected. However, if you input "the", "painful", or "truth" into the bar it will come back with zero results.(P.S. "The Painful Truth" is the first entry in the table) I attempted to debug it by listing out the song names in the table, the search, and the array after exploding the song names. They all line up like they should work, but alas, they don't.
The code below takes the input and removes characters and spaces
$lower = strtolower($_POST["text"]);
$characterRemover = preg_replace('/[^ \w]+/', '', $lower);
$search = str_replace(' ' , '' , $characterRemover);
echo "<strong>". $search . "</strong><br>";
The code below takes data from the database, explodes the string and tries to find a match.
while($row = $result->fetch_assoc()) {
$Slower = strtolower($row["song_name"]);
echo "Song Name: " . $Slower . "<br>";
$song_name = explode(" " , $Slower);
// list array
$arrlength = count($song_name);
for($x = 0; $x < $arrlength; $x++) {
echo $song_name[$x];
echo "<br>";
}
if (in_array($search, $song_name) !== false) {
$song_result = $row["song_name"];
} else {
$song_result = "0 results buddy";
}
}
here's how it looks when I search for "the":

What's happening here is that the loop is running for every single row and the variable $song_result is being overwritten. Try to use a flag $found to get the song.
$found = false;
while(!$found && ($row = $result->fetch_assoc())) {
$Slower = strtolower($row["song_name"]);
echo "Song Name: " . $Slower . "<br>";
$song_name = explode(" " , $Slower);
// list array
$arrlength = count($song_name);
for($x = 0; $x < $arrlength; $x++) {
echo $song_name[$x];
echo "<br>";
}
if (in_array($search, $song_name) !== false) {
$song_result = $row["song_name"];
$found = true;
} else {
$song_result = "0 results buddy";
}
}
If you want to capture every song, then use an array or concatenate a string:
$songs = [];
while($row = $result->fetch_assoc()) {
$Slower = strtolower($row["song_name"]);
echo "Song Name: " . $Slower . "<br>";
$song_name = explode(" " , $Slower);
// list array
$arrlength = count($song_name);
for($x = 0; $x < $arrlength; $x++) {
echo $song_name[$x];
echo "<br>";
}
if (in_array($search, $song_name) !== false) {
$songs[] = $row["song_name"];
}
}
if (count($songs)) {
$song_result = implode('<br>', $songs);
} else {
$song_result = "0 results buddy";
}
Note: You should follow JimL's suggestion and request the info filtering the DB query via the WHERE clause. And then just show the result of the query. ;)

<?php
//Kindly make sure you have create a connection and select a db. this is a sample code to search from mysql db using data supplied
$msg=$_POST['search'];
if(isset($msg)){
$search=explode(' ',$msg);
$len=count($search);
$query="select * from news where ";
for($m=0;$m<$len;$m++){
$query.=" post like '%{$search[$m]}%' || ";
}
$query.=" post like '%{$msg}%' order by upload_date desc";
if($get=mysqli_query($connect,$query)){
$contentSearch=array();
$i=0;
while($row=mysqli_fetch_assoc($get)){
contentSearch[$i]=$row;
$i++;
}
echo"List of Search Items<br>";
print_r($contentSearch);
}
}

Related

Loop from array not executed

I am working on an android app that should create some records on a MySQL database.
This is the PHP file that receives the POST values from the app.
As you may see, there are three arrays that collect specific POST.
The first and second loops are working fine and executing the related guardar_post_media() function.
But the third loop is not executed and there are real values on the variables inside the third array.
May be there is something wrong that I canĀ“t detect, may be you can.
<?php
require_once '../mis_php_functions/funciones_basicas.php';
if($_SERVER['REQUEST_METHOD']=='POST'){
$val39 = $_POST['val39'];
$val40 = $_POST['val40'];
$val46 = $_POST['val46'];
$val48 = $_POST['val48'];
$val50 = $_POST['val50'];
$val52 = $_POST['val52'];
$val54 = $_POST['val54'];
$val56 = $_POST['val56'];
$val58 = $_POST['val58'];
$val60 = $_POST['val60'];
$val62 = $_POST['val62'];
$val64 = $_POST['val64'];
$val65 = $_POST['val65'];
$val67 = $_POST['val67'];
$val69 = $_POST['val69'];
$val71 = $_POST['val71'];
$val73 = $_POST['val73'];
$val75 = $_POST['val75'];
$val77 = $_POST['val77'];
$val79 = $_POST['val79'];
$val81 = $_POST['val81'];
$val82 = $_POST['val82'];
$val83 = $_POST['val83'];
$val84 = $_POST['val84'];
$val85 = $_POST['val85'];
$val86 = $_POST['val86'];
$val87 = $_POST['val87'];
$val88 = $_POST['val88'];
$val89 = $_POST['val89'];
$val100 = $_POST['val100'];
$val101 = $_POST['val101'];
$val102 = $_POST['val102'];
$val103 = $_POST['val103'];
$val104 = $_POST['val104'];
$status = 1;
$post = guardar_post($val40,$val39,$val100,$val102,$status,$val103);
if ($post != false) {
$fotos = array($val48,$val50,$val52,$val54,$val56,$val58,$val60,$val62,$val64);
$arrayLength = count($fotos);
echo "Numero de fotos ".$arrayLength;
$i = 0;
while ($i < $arrayLength)
{
if ($fotos[$i] == 0){
}
else{
guardar_post_media(1,$fotos[$i],$val102,$val100,$post);
}
echo "<br />".$fotos[$i] ."<br />";
$i++;
}
$videos = array($val67,$val69,$val71,$val73,$val75,$val77,$val79,$val81,$val83);
$arrayLength2 = count($videos);
echo "Numero de videos ".$arrayLength2;
$i = 0;
while ($i < $arrayLength2)
{
if ($videos[$i] == 0){
}
else{
guardar_post_media(2,$videos[$i],$val102,$val100,$post);
}
echo "<br />".$videos[$i] ."<br />";
$i++;
}
$youtube = array($val85,$val86,$val87,$val88,$val89);
$arrayLength3 = count($youtube);
echo "Numero de youtube ".$arrayLength3;
$i = 0;
while ($i < $arrayLength3)
{
if ($youtube[$i] == 0){
}
else{
guardar_post_media(3,$youtube[$i],$val102,$val100,$post);
}
echo "<br />".$youtube[$i] ."<br />";
$i++;
}
sendMessageNuevoPost($val39,$val102,$val103,$val104); // envio de push
}
else{
echo 'error';
}
}
?>
You have:
if ($youtube[$i] == 0){
}
else {
}
But POST vars are all strings. Change to:
if ($youtube[$i] == "0"){
}
else {
}
In otherwords, an equality on a string to numerical 0 will be true in your cases. And thus your else never executes.
*** Edit. PROOF
$test1 = "filename.dat";
$test2 = "2939";
$test3 = "some useful data";
$test4 = "0";
if ($test1 == 0) {
// Dont do anything
}
else {
echo "Do Work 1.";
}
if ($test2 == 0) {
// Dont do anything
}
else {
echo "Do Work 2.";
}
if ($test3 == 0) {
// Dont do anything
}
else {
echo "Do Work 3.";
}
if ($test4 == 0) {
// Dont do anything
}
else {
echo "Do Work 4.";
}
Only echoes out Do Work 2.. All other echo()s are not run because the equality of a string to a number 0 will return true except in those cases where the string also is numerical, and then the interpreter will compare the numerical values.
As how this relates to the OP's question: It can be inferred that the OP's POST vars must contain some non-numerical data because the OP insists that the 3rd array is populated:
But the third loop is not executed and there are real values on the variables inside the third array.
I will add likely the loop is executed, but not giving the expected the results due the reasons so mentioned.
Tested on PHP 5 and 7.

Restrict Search Domain

I have a data set that I'm searching for certain IPA symbols. I'd like to restrict the search domain in accordance with the value of $where shown in the code below, but don't know how. EDIT: Where $where is "onset" "nucleui" and "coda." Does anyone know how to restrict the search domain? (The code below is in php but the file is linked to an HTML file that a person could use to search for the IPA symbols in the data set.) EDIT: See added code at bottom.
//set up variables
$words = $table[0]; //row 1 of table
$target = $table[1]; //row 2
$indices = array(); //used to store column numbers
$IPAstr = $_POST["ipa"];
$where = $_POST["where"];
//Find $IPAstr in $target
for($i=1; $i<count($target); $i++)
{
if (mb_strpos($target[$i],$IPAstr) !== false)
$indices[] = $i;
}
//List realizations & count frequency
for($i=0; $i<count($indices); $i++)
{
$index = $indices[$i];
$ipalist = array();
echo "<table border=1><tr><td>".$target[$index]." in " . $words[$index]."</td></tr><td>";
//output each speaker and count frequency
for ($j=2; $j<count($table); $j++) {
echo ($j-1).": ".$table[$j][$index]."<br>";
$ipalist[$table[$j][$index]]++;
}
echo "<br>";
//output frequency list
foreach($ipalist as $ipa=>$fre)
echo "$ipa: $fre<br>";
echo "</td></tr></table>";
}
//Code to help search for "onset" "nuclei" and "coda"
//list onsets only
echo "Onsets only<br>";
for($col=0; $col<count($table[0]); $col++) {
$s = $table[0][$col];
if (whichSyllPart($s) == 'o') echo "$s ";
}
//list nuclei only
echo "Nuclei only<br>";
for($col=0; $col<count($table[0]); $col++) {
$s = $table[0][$col];
if (whichSyllPart($s) == 'n') echo "$s ";
}
//list codas only
echo "Codas only<br>";
for($col=0; $col<count($table[0]); $col++) {
$s = $table[0][$col];
if (whichSyllPart($s) == 'c') echo "$s ";
}
In order to restrict the search domain you need to enter the following code as part of the "//Find $IPAstr in $target" section of the code.
//Find $IPAstr in $target
for($i=1; $i<count($target); $i++)
{
if ($where == whichSyllPart($words[$i])){
if (mb_strpos($target[$i],$IPAstr) !== false)
$indices[] = $i;
}
else if ($where == "everywhere"){
if (mb_strpos($target[$i],$IPAstr) !== false)
$indices[] = $i;
}
}
For this to run you need a function whichSyllPart()
function whichSyllPart($sy)
{
$pt = $sy[strlen($sy)-1];
return($pt);
}
This adds an if/else if statement including the whichSyllPart() function that restricts the search according to the value of $where.

PHP: Undefined offset in stripos

Hello! Im working with AJAX with DB and when trying to render my db in an option and select tag it gives me an "Undefined offset error".
Here is my code:
$sql = "SELECT word FROM words";
$result = mysql_query($sql);
$response = "";
$size = 0;
if($result === FALSE) {
die(mysql_error());
}
while ($row = mysql_fetch_array($result)) {
for($i = 0; $i < count($row); $i ++) {
$pos = stripos(strtolower($row[$i]), $pattern); //Here marks the error
if(!($pos === false)) {
$size ++;
$word = $row[$i];
$response .= "<option value=\"$word\">$word</option>";
}
}
}
if($size > 0) {
echo "<select id=\"list\" size=$size onclick=\"selectValue()\">$response</select>";
}
The idea of this app is you can start typing any word and it will search for words that matches with the input, displaying it first in an option HTML tag and when no more options are matched it's displayed in a select HTML tag.
It's kind of working but it displays this errors. Can someone help me? Thanks!!
Here is modified script:
while ($row = mysql_fetch_assoc($result)) {
$pos = stripos(strtolower($row['word']), $pattern);
if(!($pos === false)) {
$size ++;
$word = $row['word'];
$response .= "<option value=\"$word\">$word</option>";
}
}
But actually next script will run faster:
if ($result = mysql_query("SELECT word FROM words where word like '%".mysql_real_escape_string($pattern)."%'")) {
$response = "";
$size = 0;
while ($row = mysql_fetch_assoc($result)) {
$size ++;
$word = htmlspecialchars($row['word']);
$response .= "<option value=\"$word\">$word</option>";
}
echo "<select id=\"list\" size=$size onclick=\"selectValue()\">$response</select>";
}
And yes - use mysqli instead of mysql, mysql_ functions are deprecated.

Multi dimensional array. What am I doing wrong?

I have a function:
function getDecision($num_players, $decisionType, $stage){
echo "in the function 1: ".$num_players."<br/>";
echo "in the function 2: ".$decisionType."<br/>";
echo "in the function 3: ".$stage."<br/>";
$x = mysql_query("
SELECT `decisionValue` FROM `teamdecision` WHERE `decisionType` = '$decisionType' && `period`= '$stage'
")or die($x."<br/><br/>".mysql_error());
$y = array();
$i="0";
while ($i<($num_players) && $row = mysql_fetch_assoc($x))
{
$y[$i] = $row['decisionValue'];
$i++;
}
return ($y);
}
Y will be populated with a number of values depending on the $num_players. I am calling the function as follows:
$value = array();
$name = array();
for ($j=0;$j<$num_players;$j++){
for ($i=0;$i<4;$i++){
$name[0] = "SUconsultant";
$name[1] = "marketT";
$name[2] = "sector";
$name[3] = "saleprice";
echo $name[$i]."<br/>";
$value[$i] = getDecision($num_players, $name[$i], $currentStage)."<br/>";
echo "Value = ".$value[$j][$i]."<br/>";
}
}
As you can see I am doing this wrong. I need to output the data located in $value however I am confused with how multi dimensional arrays work. I understand I need to read up on the subject, if possible can you point me to a suitable learning source?
So I changed up the code so that the following is being used to produce an output below:
$value = array();
$name = array();
for ($j=0;$j<$num_players;$j++){
for ($i=0;$i<4;$i++){
$name[0] = "SUconsultant";
$name[1] = "marketT";
$name[2] = "sector";
$name[3] = "saleprice";
echo $name[$i]."<br/>";
$value[$i] = getDecision($num_players, $name[$i], $currentStage)."<br/>";
echo "Value = ".$value[$j][$i]."<br/>";
}
}
I expected to output as follows:
$value[0] should contain $y which then contains each SUconsultant value. $value[1] should contain $y which then contains each marketT value and so on.
for ($i=0;$j<4;$i++){
should be
for ($j=0;$j<4;$j++){
And
$value[$i] = getDecision($num_players, $name[$i], $currentStage)."<br/>";
should be
$value[$j] = getDecision($num_players, $name[$j], $currentStage)."<br/>";
You have a $j in your first for loop, but setting and incrimenting $i in it. Maybe change them to $j as well.
EDIT
It actually looks like you have an issue with where you are returning the data:
echo "Value = ".$value[$j][$i]."<br/>";
This should be (it appears):
for ($f = 0; $f < $num_players; $f++){
echo "Value = ".$value[$i][$f]."<br/>";
}
Since you are currently on $value[$i] by the time you reach this point, then you need it to echo out one for each player.
This solution worked, after a lot of playing around it seems that the [] after of
the value array was also needed? At least I think so
$value = array();
$name = array();
for ($j=0;$j<$num_players;$j++){
for ($i=0;$i<4;$i++){
$name[0] = "SUconsultant";
$name[1] = "marketT";
$name[2] = "sector";
$name[3] = "saleprice";
echo $name[$i]."<br/>";
$value[] = getDecision($num_players, $name[$i], $currentStage);
//echo "Value = ".$value[$i]."<br/>";
echo "<br/><hr/>";
echo "Value = ".$value[$i][$j]."<br/><hr/>";
}
}
Output:
And now I have changed to:
$value[] = getDecision($num_players, $name[$i], $currentStage);
echo "Team ".$j." ".$name[$i]." = ".$value[$i][$j]."<br/>";
To get my eventual goal of:

how do I print the line which contains the word from preg_match?

A field in mysql table "server_var_dump" which contains many details including USER_AGENT of the visitors of site. Now I only need USER_AGENTs containing line. Now I have written following script to match the USER_AGENT of the output string.
Now I need to print only those lines which contains the USER_AGENT
$result = mysql_query("SELECT server_var_dump FROM pageviews LIMIT 0,10");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
//printf("%s", $row["server_var_dump"]);
if(preg_match("/[USER_AGENT]/", $row["server_var_dump"])){
echo "match found.";
}
else
echo "No matches found";
}
Please suggest me how do I print the line which contains USER_AGENT?
Thanks!
What's wrong with just printing the row once you got it?
$match_found = false;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if(preg_match("/[USER_AGENT]/", $row["server_var_dump"])){
echo $row["server_var_dump"];
$match_found = true;
break;
}
}
if(!$match_found) {
echo "No matches found";
}
Alternatively, you'll need to get the matched values like so:
$match_found = false;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$matches = array();
if(preg_match("/[USER_AGENT](.+)/", $row["server_var_dump"], $matches)){
echo $matches[1];
$match_found = true;
}
}
if(!$match_found) {
echo "No matches found";
}
if(preg_match("/.*\[USER_AGENT\].*/" //don't forget escape [ and ] chars as Salaman A said
, $row["server_var_dump"],$matches)){
//. is every char except newline char, So,you should get all string
echo "match found.";
//use $matches[0]
}
else
echo "No matches found";
Example:
preg_match('/.*a.*/',"bc\nbac\nxy",$m);
print($m[0]); //prints bac
ok part of o/p is something like this: http://pastebin.com/e1qHG64Q
when I give
$result = mysql_query("SELECT server_var_dump FROM pageviews LIMIT 0,10");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$found = false;
$lines = explode("\n", $row["server_var_dump"]);
// $lines = explode("\\n", $row["server_var_dump"]);
for ($x = 0; $x < count($lines); $x++) {
if(preg_match("/[HTTP_USER_AGENT]/", $row["server_var_dump"])==TRUE)
//if (strstr($lines[$x], "[USER_AGENT]")==TRUE)
{
echo $lines[$x];
$found = true;
break;
}
}
it gives me o/p like array array array array
and when the strstr is given as suggested it gives o/p like array ( array ( array (
. exploding the o/p with /n is probably not working.. any other kinda hack I can do to get just the USER_AGENT line from it?
got the hack! ;)
$result = mysql_query("SELECT server_var_dump FROM pageviews LIMIT 0,10");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$found = false;
$data=str_replace("=>"," ",$row["server_var_dump"]);
$lines = explode("\n", $data);
// $lines = explode("\\n", $row["server_var_dump"]);
str_replace("\n"," ",$row["server_var_dump"]);
for ($x = 0; $x < count($lines); $x++) {
if(preg_match("[HTTP_WAP_CONNECTION]", $lines[$x])==TRUE){
//if (strstr($lines[$x], "[USER_AGENT]")==TRUE)
//{
//if(strpos($lines[$x],"[HTTP_USER_AGENT]")){
//echo substr($lines[$x],18);
$y=$x-1;
echo "$lines[$y] \n";
}

Categories