dongzhouzhang8696 2018-08-27 16:07
浏览 106
已采纳

使用PHP / PDO从MySQL创建单个数组

I am trying to create a single array from a db table that has few rows like:

--------------
id   |   name
--------------
1    | value 1
2    | value 2
3    | value 3
--------------

I want the created array to be as simple as possible like value1,value2,value3

I am using this function

function getAll()
    {
        //select all data
        $sql = "SELECT name FROM " . $this->table_name . "  ORDER BY id";

        $prep_state = $this->db_conn->prepare($sql);
        $prep_state->execute();

        $row = $prep_state->fetch(PDO::FETCH_ASSOC);
        $this->name = $row['name'];
    }

Is there a simple way to do it, perhaps with another PDO Mode like for example is done with PDO::FETCH_UNIQUE, or a should take a different approach?

UPDATE - This way it worked (thanks to @u_mulder)

function getAll()
{
    $sql = "SELECT name FROM " . $this->table_name . "  ORDER BY id";
    $prep_state = $this->db_conn->prepare($sql);
    $prep_state->execute();

    $names = $prep_state->fetchAll(PDO::FETCH_COLUMN, 0); 
    return(implode(",",$names));

}
  • 写回答

3条回答 默认 最新

  • douchi5822 2018-08-27 16:16
    关注

    What you need is PDO::FETCH_COLUMN mode:

    $sql = "SELECT name FROM " . $this->table_name . "  ORDER BY id";
    $prep_state = $this->db_conn->prepare($sql);
    $prep_state->execute();
    
    // 0 indicates first column of result
    $names = $prep_state->fetchAll(PDO::FETCH_COLUMN, 0); 
    print_r($names);
    // then do what you want.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何制作永久二维码,最好是微信也可以扫开的。(相关搜索:管理系统)
  • ¥15 delphi indy cookie 有效期
  • ¥15 labelme打不开怎么办
  • ¥35 按照图片上的两个任务要求,用keil5写出运行代码,并在proteus上仿真成功,🙏
  • ¥15 免费的电脑视频剪辑类软件如何盈利
  • ¥30 MPI读入tif文件并将文件路径分配给各进程时遇到问题
  • ¥15 pycharm中导入模块出错
  • ¥20 Ros2 moveit2 Windows环境配置,有偿,价格可商议。
  • ¥15 有关“完美的代价”问题的代码漏洞
  • ¥15 请帮我看一下这个简易化学配平器的逻辑有什么问题吗?