如何从Mysql数据库创建和填充php数组

时间:2015-05-20 07:45:18

标签: php mysql

我有MYSQL表:

|column1|column2|column3|
|id1    |human1 |data   |
|id2    |human1 |wejkls |
|id3    |human2 |sklkls |
|id4    |human1 |sdasds |
|id5    |human2 |l;lkls |
|id6    |human3 |kkklkl |
|.......|.......|.......|
|idN    |human..|.......|

所以,我需要创建php数组:

Array {
[1] => human1
[2] => human2
[3] => human3
[N] => humanN
}

我怎样才能获得人名并填充数组?

已添加:现在我有了这段代码:

$connection = new mysqli("localhost", "admin", "password", "db");
$query = "SELECT DISTINCT `teacher` FROM school_year ";
$result = mysqli_query($connection, $query);
while ($a[] = mysqli_fetch_array($result, MYSQL_NUM)) {}
print_r($a);

print_r结果:

Array ( [0] => Array ( [0] => Ahmed A.A.) [1] => Array ( [0] => Scott P.P. ) [2] => Array ( [0] => ....)...

如何将名称作为数组中的值?我不需要打印名字,我需要它们用于其他功能。

2 个答案:

答案 0 :(得分:3)

<强> RTM

示例#1获取结果集中的所有剩余行

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?> 

答案 1 :(得分:0)

我想你想要SQL:

SELECT DISTINCT(column2) as human FROM tablename ORDER BY column2 ASC;

无论每个人有多少条目存在,这都会给你所有人一次。

替代:

SELECT columns2 as human FROM tablename GROUP BY columns2 ORDER BY column2 ASC

从那里它取决于你在PHP本身的实现,例如如果您使用PDO或mysqli或库。