Shia Blue
Shia Blue

Reputation: 19

How to store session variable in database

I am actually new to PHP. My problem is that the session does not store in my database.

here's is my demo_session1.php

<?php
$Refno="";
// Start the session
session_start();

$_SESSION["$Refno"] = "HNo1";
echo "Ref no.:HNO1";

if(isset($_POST['submit']))
{
   $Refno  = $_POST['Refno'];

}
?>

<html>
<body>
<a href="demo_session2.php">Arrange to view property</a>

</body>
</html> 

here's my demo_session2.php:

<?php
$Refno = $message= ""; 
$messageErr = "";

session_start();
require "configdemo.php";
echo "Ref no.: " . $_SESSION["$Refno"] . ".<br>";

if(isset($_POST['submit']))
{
$Refno  = $_POST['Refno'];
$message = $_POST['message'];
}

 if (empty($_POST["message"])) 
{
     $messageErr = "Please leave a message for the agent.";
   }

else
{

 $sql = mysqli_query($con,"INSERT INTO demo (Refno, message) VALUES 

('$Refno' , '$message') ") or die("Can't Insert! ");
          header ("location: thanks.php"); 
         }

?>
<style>
.error {
color: #FF0000;
font-size:12px;
text-transform: lowercase;
}
</style>
<!DOCTYPE html>
<html>
<body>
<table width="100%" align="center" cellpadding="0" cellspacing="1" >
<form name="viewing_form" method="post" action="">
<tr>
<td>Message: <td><textarea name="message"rows="5" cols="25" value="<?php echo 

$message;?>"></textarea>
<td><span class="error"> <?php echo $messageErr;?></span></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit"></td>
<td><input type="submit" name="cancel" value="Cancel"></td>
</body>
</html> 

The "Refno" displays on the demo_session2.php, but when I press the submit button only the message is inserted into the database. I want also the "Refno" to be inserted.

Upvotes: 1

Views: 2350

Answers (1)

Marc
Marc

Reputation: 3709

  • Remove the $ Sign from $_SESSION Refno (as Vincent mentioned)
  • If I see this correctly, your form does not contain a field with the name "Refno". So there will be no $_POST['Refno']. So either you add such a field or you use the SESSION in the QUERY:

    $sql = mysqli_query($con,"INSERT INTO demo (Refno, message) VALUES ('$_SESSION[Refno]' , '$message') ") or die("Can't Insert! ");

And as Karel mentioned, it would be appropriate to escape the $message with mysqli_real_escape_string()

Upvotes: 2

Related Questions