Link to home
Start Free TrialLog in
Avatar of AmitavaCh
AmitavaChFlag for India

asked on

Update form in php by using Sessions

Hi,
I am developing a small friend contact list for my personal website, wherein I want my friends to update their personal details, like address, city, phone number, email address etc. after login.
There are fields like address, city, phone No., email, which is editable and fields like Names are not editable.
Flow:
login.php-->mainpage.php [where all the fields are getting displayed in column-wise like:
      First Name:
      Last Name :
      Address     :
      City             :
      Phone        :
      Email         :

To edit or update the details, I create a link 'EDIT' Button and link it to a page 'edit_profile.php', where I want my friends to update their latest information. But, the code is not working - I am developing this myself with the help of Internet. May I request you to kindly look into this and correct, it would be a great learning experience for me.

[edit_profile.php] is attached below:
<?php
session_start();
$first_name = $_SESSION['first_name'];
$last_name  = $_SESSION['last_name'];
$Fri_Add1  = $_SESSION['Fri_Add1'];
$Fri_City  = $_SESSION['Fri_City'];
$Fri_Phone1  = $_SESSION['Fri_Phone1'];
$Fri_Email1  = $_SESSION['Fri_Email1'];


if(!isset($_SESSION['restrict'])){
header("Location: ../login.php");
}

include "database/friends.php";
$sqlInfo = mysql_query(" select * from `friends`");

if(isset($_POST['updateMessage'])){

include 'database/friends.php';
$updateMessage = trim($_POST['updateMessage']);
$first_name = $_SESSION['first_name'];
$last_name  = $_SESSION['last_name'];
$Fri_Add1     = trim($_POST['Fri_Add1']);
$Fri_City     = trim($_POST['Fri_City']);
$Fri_Phone1   = trim($_POST['Fri_Phone1']);
$Fri_Email1   = trim($_POST['Fri_Email1']);
$submit        = trim($_POST['submit']);


if($submit=='Update'){

$sql = mysql_query("Update `friends` set Fri_Add1='$Fri_Add1',Fri_City='$Fri_City',Fri_Phone1='$Fri_Phone1',Fri_Email1='$Fri_Email1' where id='$updateMessage' ");

}

}
?>
<!DOCTYPE HTML>
<html>
<head>
  <title>My Friends Contact List</title>
  <meta name="description" content="website description" />
  <meta name="keywords" content="website keywords, website keywords" />
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  <link rel="stylesheet" type="text/css" href="css/style.css" />
  <script type="text/javascript" src="js/modernizr-1.5.min.js"></script>
 
  <link rel="stylesheet" type="text/css" href="css/newdefault.css"/>
</head>

<body>
<div id="main">
    <?php include 'header.php';?>
    <div id="site_content" style='width:1200px;'>
      <?php
        include "database/friends.php";
        $sql = mysql_query("Select * from `friends` ");
        $i = 1;
        
        /*echo "<table width='950px'>";
        echo "<tr><td width='20px'><font color='#000000' size='2px'><b>Sl No</b></font></td>";
        echo "<td width='200px'><font color='#000000' size='2px'><b>First Name</b></font></td>";
        echo "<td width='200px'><font color='#000000' size='2px'><b>Last Name</b></font></td>";
        echo "<td><font color='#000000' size='2px'><b>Address</b></font></td>";
        echo "<td><font color='#000000' size='2px'><b>City</b></font></td>";
        echo "<td><font color='#000000' size='2px'><b>Phone</b></font></td>";
        echo "<td><font color='#000000' size='2px'><b>Email</b></font></td>";
        echo "<td><font color='#000000' size='2px'><b>Edit || Archive</b></font></td>";
        echo "</tr>";*/
        
        /*while($row = mysql_fetch_array($sql)){
            $id              = $row['id'];
                  $Fri_Add1      = $row['Fri_Add1'];
                  $Fri_City          = $row['Fri_City'];
                  $Fri_Email1    = $row['Fri_Email1'];
            $upDateDate    = date('d-M-Y',strtotime($row['upDateDate']));
                  $status        = $row['archive'];*/
            ?>
<h1><left>Updation of Friend's profile:</left></h1>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" onSubmit="if(!confirm('Would you really like to update')){return false;}">
      <table border="1" width="555">
   <tr>
      <input type='hidden' name='updateMessage' value='<?php echo($id);?>'>
    <td><font color='#000000' size='2px'><?php echo($i);?></font></td>
      <tr>
            <td width="200">Name</td>
            <td width="5" align="center">:</td>
            <td width="350"><?php echo($first_name." ".$last_name);?></td>
      </tr>
      <tr>
            <td width="200">Address</td>
            <td width="5" align="center">:</td>
            <td width="350"><input type='text' name='Fri_Add1' id='Fri_Add1' value='<?php echo($Fri_Add1);?>' style='height:30px;width:200px;'></td>
      </tr>
      <tr>
            <td width="200">City</td>
            <td width="5" align="center">:</td>
            <td width="350">
            <input type='text' name='Fri_City' id='Fri_City' value='<?php echo($Fri_City);?>' style='height:30px;width:200px;'></td>
      </tr>
      <tr>
            <td width="200">Contact Number (Primary)</td>
            <td width="5" align="center">:</td>
            <td width="350">
            <input type='text' name='$Fri_Phone1' id='$Fri_Phone1' value='<?php echo($Fri_Phone1);?>' style='height:30px;width:200px;'></td>
      </tr>
            <tr>
            <td width="200">Email Address (Primary)</td>
            <td width="5" align="center">:</td>
            <td width="350">
            <input type='text' name='Fri_Email1' id='Fri_Email1' value='<?php echo($Fri_Email1);?>' style='height:30px;width:200px;'></td>
      </tr>
            <tr>
            <td width="200">&nbsp;</td>
            <td width="5" align="center">&nbsp;</td>
            <td width="350">
            <input type='submit' name='submit' id='submit' value='Update' style='background-color:#D3E7F5;width:60px;height:30px;'></td>
      </tr>
      </tr>
      </table>
      </form>
      <?php
         $i = $i+1;            
      
          ?>
</div>
</div>
</body>
</html>
update_friend_list.php
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Hey there,

Sorry to say this, but there's quite a bit wrong with your code. The first thing of note is that you're still using the out-dated mysql extension. This has been deprecated so if you're developing new code, you shouldn't be using it. You should switch to using mysqli or PDO (my preference). As you're updating a database with user-entered data, you should also be parameterising your queries. This will prevent any SQL injection and keep your script more secure.

You look to be storing your friends data in the session, but I would recommend only storing their ID in the session, and then pulling the data out of the database based on that ID. Once you've got that data, you can display it in your form, and then when they submit that form, update the database, again based on the session id.

Here's a quick demo on the way you should be heading:

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
 
// Connect to the DB
$hostname = 'localhost';
$username = 'yourUserName';
$password = 'yourPassword';
$database = 'yourDatabase';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
    $dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch(PDOException $e) {
    echo $e->getMessage();
}

// Handle the POST actions
if (isset($_POST['action']))
{
    // We need to update the user first
    if ($_POST['action'] == "update")
    {
        // Get the users data from the POST array
        $userData = array(
            'id' => $_SESSION['userId'],
            'add1' => $_POST['add1],
            'city' => $_POST['city']
        );

        // Prepare and execute the query
        $updateUser = $dbh->prepare('UPDATE friends SET Fri_Add1 = :add1, Fri_City = :city WHERE id = :id LIMIT 1');
        $updateUser->execute($userData);
    }    

    $userData = array(
        'id' => $_SESSION['userId']
    );

    // Get the user info from the database
    $selectUser = $dbh->prepare('SELECT firstname, lastname, Fri_Add1, Fri_City FROM friends WHERE id = :id LIMIT 1');
    $selectUser->execute($userData);

    $user = $selectUser->fetch();
}
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Chris Stanyon</title>
    </head>

    <body>
        <pre>
            <!-- let's see what was POSTed -->
            <?php var_dump($_POST); // REMOVE FROM PRODUCTION ?>
        </pre>

        <!-- do we have some user info? -->
        <?php if (!empty($user)) : ?>

            <!-- have a look at the user info from the DB // REMOVE FROM PRODUCTION -->
            <?php var_dump($user); ?>

            <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
                <table>
                    <tr>
                        <td>First Name:</td>
                        <td><?php echo $user->firstname ?></td>
                    </tr>
                    <tr>
                        <td>Last Name:</td>
                        <td><?php echo $user->lastname ?></td>
                    </tr>
                    <tr>
                        <td>Address:</td>
                        <td><input type="text" name="add1" value="<?php echo $user->Fri_Add1 ?>"></td>
                    </tr>
                    <tr>
                        <td>City:</td>
                        <td><input type="text" name="city" value="<?php echo $user->Fri_City ?>"></td>
                    </tr>
                    <tr>
                        <td><input type="hidden" name="action" value="update"></td>
                        <td><input type="submit" value="Update"></td>
                    </tr>
                </table>
            </form>

        <?php else: ?>

            <p>No user data found!</p>

        <?php endif; ?>
    </body>
</html>

Open in new window

This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.