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

}

图片转代码服务由CSDN问答提供 功能建议

我正在尝试从db表创建一个单行数组,其中包含几行: <前> -------------- id | name -------------- 1 | 值1 2 | 值2 3 | 值3 --------------

我希望创建的数组尽可能简单,如value1,value2 ,value3

我正在使用此函数

  function getAll()
 {
 //选择所有数据
 $ sql  =“SELECT name FROM”。  $ this-&gt; table_name。  “ORDER BY id”; 
 
 $ prep_state = $ this-&gt; db_conn-&gt; prepare($ sql); 
 $ prep_state-&gt; execute(); 
 
 $ row = $ prep_state-&gt  ; fetch(PDO :: FETCH_ASSOC); 
 $ this-&gt; name = $ row ['name']; 
} 
   
 
 

是否有一个简单的 这样做的方法,也许用另一个PDO模式,例如用PDO :: FETCH_UNIQUE完成,或者应该采用不同的方法?

UPDATE - 这个 它的工作方式(感谢@u_mulder

  function getAll()
 {
 $ sql =“SELECT name FROM”。  $ this-&gt; table_name。  “ORDER BY id”; 
 $ prep_state = $ this-&gt; db_conn-&gt; prepare($ sql); 
 $ prep_state-&gt; execute(); 
 
 $ names = $ prep_state-&gt; fetchAll  (PDO :: FETCH_COLUMN,0);  
 return(implode(“,”,$ names)); 
 
} 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题