Why does this query only show one result?

后端 未结 3 1408
闹比i
闹比i 2021-01-24 08:19

The query below will be used a search script. For some reason it won\'t return all results where either condition is true. What am i doing wrong?

$sql = \"SELE         


        
相关标签:
3条回答
  • 2021-01-24 08:31

    You are printing outside of while. Which means, no matter how many results you have, only the one will be printed.

    Either print inside the loop

    while($row = mysql_fetch_array($query))
    {
        $name = htmlspecialchars($row['name']);
        $code = htmlspecialchars($row['id_code']);
        print("$code: $name<br /> <br />");
    }
    

    or collect the variables in an array while looping and use them after the loop as you like

    $result_array = array();
    while($row = mysql_fetch_array($query))
    {
        $name = htmlspecialchars($row['name']);
        $code = htmlspecialchars($row['id_code']);
    
        $result_array[] = array(
            'name' => $name,
            'code' => $code
        );
    }
    print_r($result_array);
    
    0 讨论(0)
  • 2021-01-24 08:40

    You really shouldn't be using MySQL for fulltext search (see: http://en.wikipedia.org/wiki/Full_text_search). Instead, consider using MySQL's fulltext capabilities: http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html. Or possibly even better, use a "real" fulltext search engine like Lucene (see: http://lucene.apache.org/) or Sphinx (see: http://sphinxsearch.com/).

    0 讨论(0)
  • 2021-01-24 08:47

    Your loop overwrites the value of $name and $code with each loop, so all you will eventually see is the value of the last cycle.

    while( $row = mysql_fetch_array( $query ) ) {
      $name = htmlspecialchars($row['name']);
      $code = htmlspecialchars($row['id_code']);
    }
    

    You can either echo those values from within your loop, or push them onto a collection someplace:

    while ( $row = mysql_fetch_array( $query ) ) {
      $names[] = htmlspecialchars( $row["name"] );
      $codes[] = htmlspecialchars( $row["id_code"] );
    }
    

    Or you could put both values into a single array:

    $set = array();
    while ( $row = mysql_fetch_array( $query ) ) {
      $set[] = array( 
        "Name" => htmlspecialchars( $row["name"] ),
        "Code" => htmlspecialchars( $row["id_code"] )
      );
    }
    

    At this point, you have loaded all of the names and codes into arrays (or an array) that can be manipulated after your loop has run its course.

    print_r( $names ); // or $set
    

    Redundant Actions

    Additionally, you have some redundant code:

    $result = mysql_query($sql);
    $query  = mysql_query($sql) or die ("Error: ".mysql_error());
    

    This runs your query twice - no need for that.

    $num_rows1 = mysql_num_rows($result);
    $rows = mysql_num_rows($result);
    

    This is counting the number of rows returned, twice. Again, no need for that.

    0 讨论(0)
提交回复
热议问题