【问题标题】:How to create and fill php array from Mysql database如何从 Mysql 数据库创建和填充 php 数组
【发布时间】:2015-05-20 07:45:17
【问题描述】:

我有 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] => ....)...

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

【问题讨论】:

  • 您为实现这一目标做了哪些尝试? - 这是非常基本的 php / db 交互,有很多教程向您展示如何做到这一点。
  • 获取一些关于在php中选择查询的课程
  • SELECT DISTINCT ... 其余的你必须自己拥有。

标签: php mysql


【解决方案1】:

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);
?> 

【讨论】:

    【解决方案2】:

    我想你想要 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 或库。

    【讨论】:

      猜你喜欢
      • 2014-02-07
      • 2012-09-06
      • 2016-10-04
      • 2015-10-11
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-07
      相关资源
      最近更新 更多