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.
Related
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.
I need to search every word of an string in the database. If an word exist it needs to be highlighted. The current script works, but needs a lot of memory for my server. I don't know how i make it easier, but maybe do you?
<?php
$total_messages = $_POST['total'] - 1;
for($x = 0; $x <= $total_messages; $x++)
{
//Search highlights
$result = $mysqli->query("SELECT * FROM highlights WHERE enabled=1")
while($row = $result->fetch_assoc())
{
//Vars for highlights
$highlight_txt = $row['value'];
$highlight_type = $row['type'];
$highlight_color = "black";
$highlight_title = null;
//If the text isnt empty
if($highlight_txt != null || $highlight_txt != "")
{
//Type highlights
if($highlight_type == "tree") //Tree type
{
$highlight_type = "18"; //Category number
$highlight_background = "pink"; //Background
if($row['option1'] != null)
{
$highlight_title = htmlentities($row['option1']);
}
}
else
{
$highlight_background = "yellow"; //Background
}
//Add highlight
$message = preg_replace("/\b($highlight_txt)\b/i", "<span class='bc_highlight' highlight-type='$highlight_type' highlight-value='$highlight_txt' style='background: $highlight_background; color: $highlight_color;' title=''>$highlight_txt</span>", $message);
}
}
echo $message; //Display the message
}
Why not doing something like this?
$messages = ["This is my message1","This is my message2"];
$highlights = [];
$result = $mysqli->query("SELECT * FROM highlights WHERE enabled=1")
while($row = $result->fetch_assoc()) {
$highlights[$row["value"]] = [
"type" => $row["type"],
"color" => $row["color"]
];
}
$callback = function($matches) use ($highlights) {
$word = $matches[1];
if(isset($highlights[$word])) {
$highlight = $highlights[$word];
return sprintf('<span style="color:%s">%s</span>',$highlight["color"],$word);
} else {
return $word;
}
};
foreach($messages as &$message) {
$message = preg_replace_callback("/(\w+)/i",$message,$callback);
}
Well, basically what this code does is grab some links from a source code of a website and send them to an mp3 player.
The big problem is on the get_link function, where i want to store the urls to an array. The section where im having problems is commented.
Sorry for posting all this code but the functions are connected to each others.
function getHost($db,$id){
if(isset($_GET['id'])){
$sql1 = "SELECT host FROM mixtape WHERE id=?";
$stm = $db->prepare($sql1);
$stm->execute(array($id));
$row1 = $stm->fetch(PDO::FETCH_ASSOC);
if($row1['host']=='host1'){
$sql2 = "SELECT link1 FROM faixa WHERE id_mixtape IN(SELECT id FROM mixtape WHERE id=?)";
$stm = $db->prepare($sql2);
$stm->execute(array($id));
$rows_affected = $stm->rowCount();
$array=array();
if (count($rows_affected) > 0) {
for($i=1; $i <= $rows_affected; $i++) {
$row2 = $stm->fetch(PDO::FETCH_ASSOC);
$url=$row2['link1'];
get_Link($db,$url,$i,$rows_affected,$array);
}
}
}
}
}
function get_Link($db,$url,$pos,$rows_affect,$array){
$find = 'url:';
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$data = file_get_contents($url);
$data = explode("\n", $data);
for ($line = 0; $line < count($data); $line++) {
if (strpos($data[$line], $find) !== false) {
$link = preg_replace($reg_exUrl,"", $data[$line]);
$v[]=$link;
}
}
if($pos!=$rows_affect-1){
$url="mylink.com/".$link."|";
}else{
$url="mylink.com/".$link."&";
}
$array[$pos]=$url;
var_dump($array); // Here says that are 3 values in the array. True
if($pos==$rows_affect-1){
var_dump($array); // Here is only showing the last value in the array. Why?
player($db,$array);
}
}
function player($db,$array){
if(isset($_GET['id'])){
foreach($array as $i=>$item){
echo $item;
}
}
}
This piece of code:
$c=0;
for ($line = 0; $line < count($data); $line++) {
if (strpos($data[$line], $find) !== false) {
$link = preg_replace($reg_exUrl,"", $data[$line]);
$v[$c]=$link;
}
}
Should be like:
$c=0;
for ($line = 0; $line < count($data); $line++) {
if (strpos($data[$line], $find) !== false) {
$link = preg_replace($reg_exUrl,"", $data[$line]);
$v[$c]=$link;
$c = $c+1; //this is missing or $c++;
}
}
OR:
for ($line = 0; $line < count($data); $line++) {
if (strpos($data[$line], $find) !== false) {
$link = preg_replace($reg_exUrl,"", $data[$line]);
$v[]=$link; //That way works too
}
}
Miguelfsf, you must first learn about variable scope.
Your problem is, you created the $array=array() (the $array show be the $row2).
You declared a new variable, but you didn't used, the $array was just to tell you, declare your array that way
$row2=array().
After that you need to do
$row2[] = $stm->fetch(PDO::FETCH_ASSOC);
Why?
Because the assoc returns a associative array, then it will do
$array => {title => "last title} = $newData => {title => "new title"}
It will replace the value
Using the [] everytime you do this it'll create a new element.
Then
{
0 => { title => "title1"}
1 => { title => "title2"}
2 => { title => "title3"}
3 => { title => "title4"}
}
I have a code where it should check if the result equals to 8 it need to show something and if not it need to show something else and all of that happens inside of a while loop.
while ($row_fpages2 = mysql_fetch_array($result_fanpage2))
{
if ( $row_fpages2['client'] != NULL ) {
//GRAPHS
$sql = "SELECT likes, date FROM statistics_pages WHERE idnum = '".$idnum."' AND page_name = '".$row_fpages2['page_name']."' ORDER BY `statistics_pages`.`date` DESC LIMIT 8";
$result2 = mysql_query($sql) or die(mysql_error());
if ($result2) {
$data = array();
while ($row = mysql_fetch_assoc($result2)) {
$data[] = $row["likes"];
}
if ($result2 == 8) {
$c_data = count($data)-1;
$final = array();
for ($i = 0; $i < $c_data; $i++) {
$final[] = getZeroResult($data[$i], $data[$i+1]);
}
$data_string = join(",", $final);
$stats = '<img src="http://chart.apis.google.com/chart?chs=240x140&cht=ls&chd=t:0,0|'.$data_string.'&chg=20,20&chls=0.75,-1,-1|6,4,1&chm=o,FF9900,1,-1,7,-1|b,3399CC44,0,1,0"></img>';
} else {
$stats = '<img src="images/stats_un.jpg"></img>';
};
} else {
print('MySQL query failed with error: ' . mysql_error());
}
echo '...';
The problem is that the first output always showing the ( == 8) (even if it is not equals to 8) instead of the else output.
Then if i have 2 or more everything comes above the first one is correct but the first one is still showing the ( == 8).
Any help?
You do the following which is incorrect:
$result2 = mysql_query($sql) or die(mysql_error());
...
if ($result2 == 8) {
The return value of mysql_query is a resource not an int. What is that you are trying to do there ?
May be you would like to use
if(strlen($result2) == 8){
...
}
instead of
if($result2 == 8){
...
}
Hope that solves your problem.
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";
}