简体   繁体   中英

How to iterate on search results from MySQL by PHP?

When I use

 function __construct()
    {
      // open db
      $this->db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
      if (!$this->db)
        die(mysql_error());

      $this->db->query("SET NAMES 'utf8';");
    }


$result=$this->db->query("SELECT OrgNo, CompanyName FROM ematch WHERE CompanyName LIKE '%$word%';");
           $num=$result->num_rows;
          print $num; 
           $i=0;
            while ($i < $num) 
            {
                 $OrgNo=mysql_result($result,$i,"OrgNo");
                 $CompanyName=mysql_result($result,$i,"CompanyName");
                 $i++;
                 print $OrgNo.' '.$CompanyName.'<br>';
            }

I get this error: Warning: mysql_result(): supplied argument is not a valid MySQL result resource and nothing comes out.

You can change your code to this:

$result = $this->db->query("SELECT OrgNo, CompanyName FROM ematch WHERE CompanyName LIKE '%$word%';");

while ($row = mysqli_fetch_array($result)) 
{
  print $row['OrgNo'] .'<br />';
  print $row['CompanyName'] .'<br />';
}

Where it is assumed that $result returned form your query method is a result resource.

You are going to have to show us the DB wrapper/class you are using but I'd like to have a guess at a way forward:

$result = $this->db->query("SELECT OrgNo, CompanyName FROM ematch WHERE CompanyName LIKE '%$word%';");
while($row = mysqli_fetch_array($result)) {
    print $row['OrgNo']." ".$row['CompanyName']."<br>";
}

As you are using a custom DB wrapper youd be better use its way of fetching rows one by one rather than using mysqli_fetch_array();

Try removing the semi-colon from your SQL statement.

"SELECT OrgNo, CompanyName FROM ematch WHERE CompanyName LIKE '%$word%';"

should probably be

"SELECT OrgNo, CompanyName FROM ematch WHERE CompanyName LIKE '%$word%'"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM