我有一个登录页面,用于收集登录时映射到某个用户的客户端。
$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()提供的参数无效
我想就如何在会话中正确存储数组提出一些建议,以便我可以将它们打印出来(将用作下拉列表等)。
答案 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 对未声明的变量大喊大叫也就不足为奇了。
那么让我们从头开始吧。
fetch()
访问结果集的单行。如果结果集为空,则返回值为$client
。建议代码:
false