2016-08-02 108 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)'。如果这是你所描述的情况,那么不要冒犯。 –

相关问题