0

Please help me solve this problem:

if($_POST["keyword"]) {
$keyword       = $_POST["keyword"];
$keyword       = trim($keyword);
$keyword_array = explode(" ",$keyword);
$numberofwords = (integer)count($keyword_array);
require("server.php");
$link = open_koneksi();
$tbl_name      = "author";
$query         = "SELECT COUNT(*) as num FROM $tbl_name WHERE " ;
   for ($x = 0; $x<= $numberofwords; $x++) {
      $query .= "author LIKE '%$keyword_array[$x]%'";
      if ( $x <  $numberofwords ) {
         $query .= " AND ";
      }
   }
   echo("<SCRIPT>document.location.href='?p=result';</SCRIPT>");

}

If the code in the program segment is executed, there will be a warning as follows:

Notice: Undefined offset: 1 in C:\xampp\htdocs\bijang\result.php on line 111

Location of faults refer to this code:

$query .= "author LIKE '%$keyword_array[$x]%'";

How do I fix this?

dogmatic69
  • 7,574
  • 4
  • 31
  • 49

3 Answers3

3

Your problem is probably this:

  for ($x = 0; $x<= $numberofwords; $x++) {
                 ##

You are counting indexes 0 till 1, because the previous count() gave you 1. But that's the total number of indexes, the last index is still 0.

Change it into:

  for ($x = 0; $x < $numberofwords; $x++) {
                  #

Better yet, just use an foreach:

  foreach ($keyword_array as $x => $kw) {

That counts the indexes in $x implicitly.
You probably still have to change your last entry detection for the AND fillers. (Commonly you first make an array of substrings, then implode() with the filler " AND ".)

YadaYada: Also take care about unfiltered input. Use the database escaping function for text strings. It's heaps easier to use PDO and prepared statements though.

mario
  • 144,265
  • 20
  • 237
  • 291
  • Thanks Mario.. after I tried to follow your advice, the next error message: Notice: Undefined variable: numberofwords in ... – Ado Bijang Jan 12 '13 at 17:09
  • You still need that count variable. – mario Jan 12 '13 at 18:33
  • See also [PHP: “Notice: Undefined variable” and “Notice: Undefined index”](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – mario Jan 12 '13 at 18:34
0

Cause the $keyword_array array don't have the $x key.

bensiu
  • 24,660
  • 56
  • 77
  • 117
Ddo
  • 389
  • 3
  • 12
0

turns out, to overcome, just one word:

error_reporting(0);

the question, whether the notice was included as part of the error?