Rajdeep Ratan Rajdeep Ratan - 3 months ago 12
MySQL Question

how to store session value in another table?

I have one login page and its database. i want to take the email from there and store it in another table of the same database. Code is give below please have a look and tell me.

Table 1

<?php
session_start();
$email = $_POST['email'];
$password = $_POST['password'];

include 'connection.php';

$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$res = mysql_query($sql);
$count = mysql_num_rows($res);

if($count == 0)
{
echo "Username Password Incorrect";
}
else
{
$_SESSION['email'] = $email;
header("location:home2.php")
}
?>


Table 2

<?php

$email= (HOW TO GET IT FROM SESSION?)

$company = $_POST['company'];
$project = $_POST['project'];
$duration = $_POST['duration'];
$key_learning = $_POST['key_learning'];

include 'connection.php';

$sql = "INSERT INTO `internship`(`id`, `email`, `company`, `project`, `duration`, `key_learning`) VALUES ('', '$email', '$company','$project', '$duration', '$key_learning')";
$res = mysql_query($sql);
$count = mysql_num_rows($res);

if($count == 1)
{
echo "Fail";
}
else
{
$_SESSION['email'] = $email;
header("location:home3.php");
}

?>


From table 1 i want to take email if using session and want to store it in table 2. How to do it?

Answer

$email= (HOW TO GET IT FROM SESSION?)

If the 2nd code block is in the same execution context as the first, you can just use the variable $email that you created.

If you're trying to retrieve data from session as the user navigates to a new page, you do:

<?php
session_start();
$email = isset($_SESSION['email'])? $_SESSION['email'] : null;

By the way, in the 2nd code block you're trying to use mysql_num_rows to analyze the effect of an INSERT query. You can't do that. According to the manual:

[mysql_num_rows] retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().

$res = mysql_query($sql) or die(mysql_error());
if(mysql_affected_rows()){
   //success
}else{
  //failure
}

You should not be using mysql_ functions anyway and you should most definitely not be inserting user provided values (username, email, password) directly in your SQL statement