将PDO :: FETCH_ASSOC结果分配给$ _SESSION变量

时间:2016-03-21 11:43:45

标签: php pdo

我有一个登录页面,用于收集登录时映射到某个用户的客户端。

            $query_acct = "select client from app_reports.user_map where user_name = '".$username."'";
            $acct = $DB_con->prepare($query_acct);
            $acct->execute();
            $row_acct = $acct->fetchAll(PDO::FETCH_ASSOC);
            if (!empty($row_acct['client'])){
                foreach($row_acct as $r) {
                    $client[] = $r['client'];
                    }
                $_SESSION['client'] = $client;
                    }

据我了解,$_SESSION['client']应该存储$client中存储的数组。 但当我试图用以下内容打印出来时:

foreach($_SESSION['client'] as $key=>$value){

    // and print out the values
    echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';

}

我得到了: 注意:未定义索引:客户端

警告:为foreach()提供的参数无效

我想就如何在会话中正确存储数组提出一些建议,以便我可以将它们打印出来(将用作下拉列表等)。

1 个答案:

答案 0 :(得分:0)

fetchAll() 返回一个数组(可能是一个空数组)。

结合String line1; String line2; int lineNumber = 0; List<Difference> differences = new LinkedList<>(); do { line1 = reader1.readLine(); line2 = reader2.readLine(); lineNumber++; //first line will have number 1 //we've hit the end of file1 if( line1 == null ) { //if we've not hit the end of file2 yet, we have a difference if( line2 != null ) { differences.add(new Difference(lineNumber, line1, line2)); } } //if we didn't hit the end of file1 yet we just compare, this will return false if: // - file2 contains a different line // - we've hit the end of file2 in which case line2 is null else if(!line1.equals(line2) { differences.add(new Difference(lineNumber, line1, line2)); } //once we've hit the end of either file we'll stop this loop } while( line1 != null && line2 != null ); //read the remaining lines of both files //since we hit the end of at least one line in the previous loop, only one of the following loops should, if at all //if we already hit the end of file1 in the first loop, line1 should be null at this point and we won't enter this loop while( line1 != null ) { line1 = reader1.readLine(); lineNumber++; differences.add(new Difference(lineNumber, line1, null)); } //if we already hit the end of file2 in the first loop, line2 should be null at this point and we won't enter this loop while( line2 != null ) { line2 = reader2.readLine(); lineNumber++; differences.add(new Difference(lineNumber, null, line2)); } 参数,如果数组不为空,那么它将包含关联数组的索引数组。

这在逻辑上意味着永远无法满足 PDO::FETCH_ASSOC。或者,!empty($row_acct['client']) 可能存在。

仅仅因为您的查询逻辑可能保证结果集中有零或一行,并不意味着 pdo 会为您返回一个扁平的行。

此外,您永远不会在条件执行循环之外声明 $row_acct[0]['client'],因此 php 对未声明的变量大喊大叫也就不足为奇了。

那么让我们从头开始吧。

  1. 在编写 mysql 关键字/函数时始终使用全部大写。
  2. 准备好的语句是无用的开销,除非您将值绑定到占位符。事实上,您的查询可能不稳定/不安全,因为您将变量直接写入 sql。
  3. 使用 fetch() 访问结果集的单行。如果结果集为空,则返回值为$client

建议代码:

false