如何在foreach循环php中传递会话值

时间:2016-09-28 10:57:43

标签: php sql

这是一个基本的事情,但我无法获得所需的数据。下面是代码,同时从登录用户ID(empid = 933)获取DB缺席计数,它给了我所需的记录。但我想用已记录的id用户的会话ID获取相同的数据,该用户已经创建为$ empid。但我无法在下面提到的查询中传递此会话值。任何人都可以提供帮助,我很感激...提前感谢你。

<?php
$hostname="localhost";  
$username="root";  
$password="";  
$db = "usman";  
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);  

foreach($dbh->query('SELECT COUNT(*) FROM ams where empid= 933 GROUP BY leavetype HAVING leavetype = "Absent"   
 ') as $Absent) 
{  
echo "<td>" . $Absent['COUNT(*)'] . "</td>";
echo "<br>"; 
}
?>

2 个答案:

答案 0 :(得分:3)

<?php
// first you must start the session to gain access to the session object
session_start();

$hostname="localhost";  
$username="root";  
$password="";  
$db = "usman";  

$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);  

foreach($dbh->query("SELECT COUNT(*) as cnt
                    FROM ams 
                    where empid= {$_SESSION['sess_user_id']} 
                    GROUP BY leavetype 
                    HAVING leavetype = 'Absent'") as $Absent) 
{  
    echo "<td>" . $Absent['cnt'] . "</td>";    
    echo "<br>"; 
}
?>

还可以更轻松地为COUNT(*)提供别名COUNT(*) as cnt,然后您可以使用$Absent['cnt']作为列名称

我也认为没有理由

GROUP BY leavetype 
HAVING leavetype = 'Absent

因为你正在使用我认为是一个唯一的id来找到ams行

答案 1 :(得分:0)

`

<?php
try{
  $db = new PDO("dbtype:host=yourhost;dbname=yourdbname;charset=utf8","username","password");
  $empid = $_SESSION['sess_user_id']; 
  $query=$db->prepare("SELECT COUNT(*) as counts FROM ams where empid= ? GROUP BY leavetype HAVING leavetype = 'Absent'");
  $query->excute(array($empid));
  while($row=$query->fetch(PDO::FETCH_OBJ)) {
   echo "<td>".$row->counts."</td>";
   echo "<br>"; 
    }
}catch(PDOException  $e ){
echo "Error: ".$e;
}
?>