2015-08-21 65 views
0

我想從while循環中獲取所有記錄。我無法從查詢中獲取所有行。它只顯示第一行。 我的代碼中有什麼問題嗎?MySQLI循環數據

function Connect($DB_HOST = 'localhost', $DB_USER = 'root', $DB_PASS = '', $DB_NAME = 'bodhilms') 
     { 
      $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME); 
      if ($mysqli->connect_errno) { 
       printf("Connect failed: %s\n", $mysqli->connect_error); 
       exit(); 
      }  
      return $mysqli; 
     } 

    function GetCoeficient($coeficient = false, $con) 
    { 
     if(!$con) 
     return 0;  

     $result = array(); 
     $sql[] = "SELECT * FROM users ";  

     if($coeficient != false) 
     $sql[] = "WHERE username = '".$coeficient."' ORDER BY u.id"; 

     //print_r($coeficient); 
     $query = $con->query(implode(" ",$sql)); 
     //print_r($query); 

     while($row = $query->fetch_assoc()) 
     { 
      $result[] = $row; 
     } 
     return (!empty($result))? $result : 0; 
    } 

    $con      = Connect(); 
    $result      = GetCoeficient($coeficient,$con); 

    $username = $result[0]['username']; 
    $firstname = $result[0]['firstname']; 
    $lastname = $result[0]['lastname']; 
    $email = $result[0]['email']; 
+0

爲什麼你會比一行多用相同的用戶名? – Barmar

+0

您正在調用'GetCourse()',但您發佈了'GetCoeficient()'的定義。你可以顯示GetCourse()的定義嗎? – Barmar

+0

調用該函數後,您只需設置'$ result [0]'中的變量,因此您只能獲得第一行。 – Barmar

回答

0

首先,要確保mysql的信息是正確的,如port。 ,我不知道你$result = Getcourse($coeficient,$con);代碼中,VAR coeficient怎麼來from.Then 你可以試試下面的代碼:

$mysqli=new mysqli("localhost","root","root","123"); 
$query="select * from test"; 
$result=$mysqli->query($query); 
if ($result) { 
     if($result->num_rows>0){ 
        while($row =$result->fetch_array()){ 
          echo ($row[0])."<br>"; 
          echo ($row[1])."<br>"; 
          echo ($row[2])."<br>"; 
          echo ($row[3])."<br>"; 
          echo "<hr>"; 
        } 
     } 
}else { 
     echo 'failure'; 
} 
$result->free(); 
$mysqli->close();