2016-08-02 32 views
-4

table如何將查詢數據放在兩個不同的數組中,然後在兩個表中回顯它?

過濾器運行select query查詢數據

如果gender equal to Man,然後把他所有的數組男性=陣列(),而它的gender is woman然後把

OR

數組woman = array()

then echo two tables

Men

1名,年齡,城市,國家等

2名,年齡,城市,國家等

3名,年齡,城市,國家等 。 。 。

Women

1名,年齡,城市,國家等

2名,年齡,城市,國家等

3名,年齡,城市,國家,等 。 。 。 。

Men表將包含這是保存在Men()陣列

Women表將包含這是保存在Women()陣列

Woman所有行數據Man所有行數據: -

我嘗試過這樣的代碼,但它的混亂,我失敗了: -

https://stackoverflow.com/questions/38653118/notice-undefined-offset-1-putting-mysql-query-data-in-while-loop

+1

編輯prevous問題不要再問 – 2016-08-02 05:55:40

+1

爲什麼你將女性與男性分開(聽起來有趣)?添加一個性別列(我會把因爲像https://40.media.tumblr.com/tumblr_lhdwd8xxRj1qak0xgo1_500的理由。jpg) –

+0

給你的代碼檢查 –

回答

1

您的查詢必須在UNION

Select men.Name, men.age, men.city, men.country, 'Male' as 'gender' FROM men_table as men UNION ALL Select women.Name, women.age, women.city, women.country, 'Female' as 'gender FROM women_table as women; 

這樣你就可以有一個查詢輸出:後

|Name |age |city |country|gender| 
---------------------------------------- 
|male1 |21  |NY  |USA |Male | 
|male2 |23  |CLV |USA |Male | 
|female1|25  |GS  |USA |Female| 
|female2|27  |CHG |USA |Female| 

可以循環到你的結果:

<?php 

$mysqli = new mysqli("localhost", "my_user", "my_password", "world"); 

/* check connection */ 
if ($mysqli->connect_errno) { 
    printf("Connect failed: %s\n", $mysqli->connect_error); 
    exit(); 
} 
    $query = "Select men.Name, men.age, men.city, men.country, 'Male' as 'gender' FROM men_table as men UNION ALL Select women.Name, women.age, women.city, women.country, 'Female' as 'gender FROM women_table as women"; 

    $men = array(); 
    $women = array; 

    if ($result = $mysqli->query($query)) { 

     /* fetch associative array */ 
     while ($row = $result->fetch_assoc()) { 
      if($row["gender"] == 'Male') { 
       $men[] = $row[]; 
      } 
      else { 
       $women[] = $row[]; 
      } 
     } 

     print_r($men); 
     print_r($women); 

     /* free result set */ 
     $result->free(); 
    } 

/* close connection */ 
$mysqli->close(); 
?> 

輸出將如下所示:

//$men array 
    array(
     [0] => array(
       'Name' => 'male1', 
       'age' => '21', 
       'city' => 'NY', 
       'country' => 'USA', 
       'gender' => 'Male' 
     ), 
     [1] => array(
       'Name' => 'male2', 
       'age' => '23', 
       'city' => 'CLV', 
       'country' => 'USA', 
       'gender' => 'Male' 
     ) 
    ); 

//$women array 
    array(
     [0] => array(
       'Name' => 'female1', 
       'age' => '25', 
       'city' => 'GS', 
       'country' => 'USA', 
       'gender' => 'Female' 
     ), 
     [1] => array(
       'Name' => 'female2', 
       'age' => '27', 
       'city' => 'CHG', 
       'country' => 'USA', 
       'gender' => 'Female' 
     ) 
    ); 
+0

你先標記我然後刪除它。爲什麼?我能知道原因嗎? –

+0

@安南我注意到他先標記了你。也許是因爲查詢?因爲他早些時候說過他有兩張桌子「男人」和「女人」,所以他可能正在尋找一個「JOIN」查詢。 IDK我的猜測可能是錯誤的 –

+0

我認爲他的數據在'one table'中,他希望以不同的方式獲取數據,並且想要顯示它像'men table(html table)'和'women table(html table)'。如果這是你所描述的情況,那麼不要冒犯。 –

相關問題