justsimpleshh justsimpleshh - 7 months ago 9
SQL Question

Creating session on login and creating variable from MySQL

I'm struggling with selecting from my database and adding it to a

$_SESSION
to carry forward onto the profile page.

Please note that the "
$_SESSION['user'] = $email;
" works and prints on the profile, but I'm sure that's because its already brought forward my the form.

Connect.php

<?php

session_start();

$required = array('email', 'password');

// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}

if ($error) {
die("All fields are required.");
} else {

//CHECK POINT 1

$con = mysql_connect("**HOST**", "**DB**", "**PASSWORD**");

mysql_select_db("**DB**")or die("cannot select DB");

// username and password sent from form
$email=$_POST['email'];
$psswrd=$_POST['password'];

// To protect MySQL injection (more detail about MySQL injection)
$email = stripslashes($email);
$psswrd = stripslashes($psswrd);
$email = mysql_real_escape_string($email);
$psswrd = mysql_real_escape_string($psswrd);
$sql="SELECT * FROM **Table WHERE email='$email' and password='$psswrd'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

//fetch info & create session
$id="SELECT 'id' FROM **table**";
$_SESSION['user'] = $email;
$_SESSION['uid'] = $id;
$_SESSION['name1'] = $fname;


Profile.php

<?php

session_start();
$email = $_SESSION["user"];
$id = $_SESSION["uid"];
$fname = $_SESSION["name1"];
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>...</head>
<body>
<div align=center><font color="#000000" face="Bodoni MT" class="ws12"><?php echo "I am ". $id. ". Contact me at ". $email ?></font></div>
</body>
</html>

Answer

You must get data from database ("$result" variable). Try this:

<?php

session_start();

$required = array('email', 'password');

foreach ($required as $field) {
    if (empty($_POST[$field])) {
        $error = true;
    } else {
        $error = false;
    }
}

if (true === $error) {
    die("All fields are required.");
} else {
    $con = mysql_connect("**HOST**", "**DB**", "**PASSWORD**");
    mysql_select_db("**DB**") or die ("cannot select DB");

    $email  = $_POST['email']; 
    $psswrd = $_POST['password']; 
    $email  = stripslashes($email);
    $psswrd = stripslashes($psswrd);
    $email  = mysql_real_escape_string($email);
    $psswrd = mysql_real_escape_string($psswrd);
    $result = mysql_fetch_assoc(mysql_query("SELECT * FROM **Table WHERE email='$email' and password='$psswrd'"));

    if (!empty($result)) {
        $_SESSION['user']  = $result['email'];
        $_SESSION['uid']   = $result['id'];   // id column name in your database
        $_SESSION['name1'] = $result['name']; // name column name in your database
    }