【问题标题】:PDO return array('value1','value2') [closed]PDO返回数组('value1','value2')[关闭]
【发布时间】:2013-01-24 03:59:24
【问题描述】:

我正在使用 select sql 语句 PDO fetchData,

$user = 'admin';
sql = 'SELECT AccessPage FROM accessrights where UserName = '$user'';

在数据库中,结果如下所示:

-----------
Access Page
-----------
 - index

 + create

 - update

我会将它存储在一个变量 $result 中

我怎样才能将 $result 格式变成这样的数组?

$result = array('index','create','update');

另一个问题,

我在我的函数中使用了代码:但是当我 var_dump 时,它会返回一个 array(0) { } 值。

这是我的功能:

    $user = CHtml::encode(Yii::app()->user->name);

    $connectionString[0] = Yii::app()->params['dbhandler2'];
    $dbhandler3 = new DBHandler($connectionString[0]);
    $dbhandler3->open();

    $dbhandler3->prepare("SELECT AccessPage FROM accessrights where UserName ='$user'");
    $dbhandler3->execute();
    $this->result2 = $dbhandler3->fetchAllData();
    $dbhandler3->close();

    $yourarrayname = array();
    while ($row = $dbhandler3->fetchAllData()) {
        $yourarrayname[] = $row['AccessPage'];
    }

    $this->access = $yourarrayname;

【问题讨论】:

  • 你应该使用准备好的语句。

标签: php mysql arrays pdo


【解决方案1】:

使用下面的代码

 $user = 'admin';
 $sql = "SELECT AccessPage FROM accessrights where UserName = '$user'";
 $sth = $dbh->prepare($sql);
 $sth->execute();

 /* Fetch all of the values of the first column */
 $result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
 print_r($result); // the $result will be array  array('index','create','update');

【讨论】:

  • 哇,我用了这段代码,它工作得很好谢谢
【解决方案2】:

我假设 indexcreateupdate 是列值,您希望它们位于“普通”数组中。默认是将结果存储为整数和列名键。您想将 fetchmode 设置为整数键:$stmt->setFetchMode(PDO::FETCH_NUM)$stmt->fetch(PDO::FETCH_NUM)http://php.net/manual/en/pdostatement.setfetchmode.phphttp://php.net/manual/en/pdostatement.fetch.php

【讨论】:

    【解决方案3】:

    首先我假设您只有一列 Accesspage 在该列中,您已经保存了三行索引、创建、更新。当您搜索用户 $userAccesspage 值时。这将返回分配给 $user 的值。

    $user = 'admin';
    $sql = 'SELECT AccessPage FROM accessrights where UserName = '$user'';
    $sth = $dbh->prepare($sql);
    $sth->execute();
    $result = $sth->fetch(PDO::FETCH_ASSOC);
    print_r($result);
    

    现在这个 $result 是一个关联数组,键为 'AccessPage'

    如果你想制作一个数组,那么你应该像这样尝试

    $yourarrayname=array();
    while ($row = $sth->fetch(PDO::FETCH_ASSOC))
    {
     $yourarrayname[]= $row['AccessPage'] ; 
    }
    
    print_r($yourarrayname);
    

    【讨论】:

    • 总是接受答案以从 stackoverflowers 获得巨大帮助!
    • 哦,我试过你上次给我的代码,但它只返回一个空数组,我在顶部编辑了我的代码
    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多