【问题标题】:why is this sql query only returning two results?为什么这个 sql 查询只返回两个结果?
【发布时间】:2014-08-23 04:16:09
【问题描述】:

我有一个 MySQL 数据库 (testDB),其中包含一个表 (info),其中包含几列、id 和 name。此表有 5 行数据。

目标是检索整个列 name 并将其值存储到数组中。问题是,它只在 $res 变量中存储了两个结果(查询的结果),实际上是两次回显它们(???)

PS:请暂时忽略$q,它将是用户输入生成的文件的查询字符串(在输入框上)

<?php

class engine {
  public function userInput() {
    $q = $_GET['q'];
    $con = mysqli_connect("localhost","root","","testDB");
    if(!$con) {
      echo "Impossible to connect: " . mysqli_errno();
    } else {
      $this->connectMe($con,$q);
    }
  }

  private function connectMe($con,$q) {
    $sql = "SELECT `name` FROM `info`"; // will select the entire column `name` on the `info` table
    $qry = mysqli_query($con,$sql); // parameter1 is the connection , parameter 2, the sql command
    $res = mysqli_fetch_array($qry); // stores the query results into an array
    foreach ($res as $value) { // loops through the array and assigns each element to $value
      $this->findMatches($value,$q); // parse each element of the array and $q to findMatches function 
    }
  }

  private function findMatches($value,$q) {
    echo "Array value: " . $value . " random query " . $q . "<br/>";
  } // WHY U NO output more than one result !!!???
}

$start = new engine(); // creates the object above
$start->userInput(); // calls the method userInput
?>

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    这不是真的:

    $res = mysqli_fetch_array($qry); // stores the query results into an array
    

    mysqli_fetch_array 获取一行,你必须把它放在一个循环中:

    while($res = mysqli_fetch_array($qry)){
      //doSomething
    }
    

    【讨论】:

      【解决方案2】:

      mysqli_fetch_array() 默认返回一个双键数组。例如

      SELECT foo, bar FROM ...
      

      会给你

      $result = array(
         'foo' => 'foo value',
         0 => 'foo value',
         'bar' => 'bar value',
         1 => 'bar value'
       );
      

      您可以在代码中使用var_dump($res) 轻松验证这一点。

      你可能想要

      mysqli_fetch_array($qry, MYSQLI_ASSOC) // field name keys only
      mysqli_fetch_array($qry, MYSQLI_NUM)   // numerica keys only
      

      改为。

      【讨论】:

        【解决方案3】:

        用这个改变foreach:

        while($res = mysqli_fetch_array($qry)) {
          $this->findMatches($value, $q)
        }
        

        【讨论】:

        • 您能解释一下您的更改工作吗?请通过给出你如何得到它们来解释你的答案中的代码。
        猜你喜欢
        • 2013-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多