douxiong5972 2014-10-13 05:39
浏览 53

PHP: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!!

  • 写回答

1条回答 默认 最新

  • duannengling4705 2014-10-13 06:12
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)