ali ak ali ak - 2 months ago 8
PHP Question

Session always returns null

I have my index.php page, which is where users can register and login. I want to display Welcome Admin once the user logs in. I have realized that session is null what can cause

$_SESSION
to become null?

<?php

session_start();

try {
$db = new PDO("mysql:host=127.0.0.1; dbname=blog", "root", "");
} catch (PDOException $ex) {
echo $ex->getMessage();
}

$v = $db->prepare("select * from uyeler where uye_sifre=? and uye_ad=?");
var_dump($v);
if ($_POST) {

$isim = $_POST["isim"];
$sifre = $_POST["sifre"];

$v->execute(array($sifre, $isim));
$x = $v->fetchAll(PDO::FETCH_ASSOC);
$d = $v->rowCount();


if ($d) {
$_SESSION["ad"] = $x["uye_ad"];
$_SESSION["sife"] = $x["uye_sifre"];
$_SESSION["durum"] = $x["uye_durum"];
echo "Giriş başarılı";
} else {
echo "Geçersiz Kullanıcı";
}

} else {
if ($_SESSION) {
var_dump($_SESSION);
echo "adam üye";
} else {

echo '<form action="" method="post">


<table cellpadding="5" cellspacing="5">
<tr>
<td>Uye Ad</td>
<td><input type="text" name="isim" id=""></td>
</tr>

<tr>
<td>Uye Şifre</td>
<td><input type="password" name="sifre" id=""></td>
</tr>
<tr>

<td><input type="submit" id=""></td>
</tr>

</table>
</form>';
}
}
?>


this is the var_dump output

wamp64\www\indeks.php:12:
object(PDOStatement)[2]
public 'queryString' => string 'select * from uyeler where uye_sifre=? and uye_ad=?' (length=51)
C:\wamp64\www\indeks.php:34:
array (size=3)
'ad' => null
'sife' => null
'durum' => null

Answer
  1. Run your query manually to see what your query returns.
  2. fetchAll returns a multidimentional array. So fix these lines

    $_SESSION["ad"] = $x["uye_ad"];
    $_SESSION["sife"] = $x["uye_sifre"];
    $_SESSION["durum"] = $x["uye_durum"];
    

    to this:

    $_SESSION["ad"] = $x[0]["uye_ad"];
    $_SESSION["sife"] = $x[0]["uye_sifre"];
    $_SESSION["durum"] = $x[0]["uye_durum"];
    

    $x is an multidimensional and looks like this:

    $x = array(
    array('uye_ad'=>'any value', 'uye_sifre'=>'any value2', 'uye_durum'=>'any value3',)
    ); 
    
Comments