Muhammad Usman Muhammad Usman - 2 months ago 9
PHP Question

How to pass session value in foreach loop php

it's a basic thing, but i am not able to get the required data. below is the code, while fetching count of absent from DB with logged in user id (empid=933) it's giving me the required record. but i want to fetch the same data with session ID of logged id user which is already created as $empid. but i am not able to pass this session value in below mentioned query. any one can help, i would appreciate ... thanking you in advance.

<?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>";
}
?>

Answer
<?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>"; 
}
?>

Its also easier to give the COUNT(*) an alias COUNT(*) as cnt then you can use $Absent['cnt'] as the columns name

Comments