John120 John120 - 3 months ago 6
MySQL Question

Data not update when login is successfull in index.php?

enter image description hereI make a login page like user login. if registered then login with email and password(navigate register.php to index.php page) or sign up if not registered. works good but i want to add update functionality in my index.php page concept is simple if user wants to update its record then he make updations in a form and submit. I make a update query here but its shows Notice: Undefined index: id in C:\wamp\www\LOginKodingMadSimple\index.php on line 34. Where i am wrong ?

index.php :

<?php
session_start();
include_once 'dbconnect.php';
?>

<?php
if (isset($_POST['UpdateUser']))
{
$name = mysqli_real_escape_string($con, $_POST['name']);
$id = mysqli_real_escape_string($con, $_POST['id']);
//------- name can contain only alpha characters and space -------
if (!preg_match("/^[a-zA-Z ]+$/",$name))
{
$error = true;
$name_error = "Name must contain only alphabets and space";
}
//------- Update users -------
if (!$error)
{
if(mysqli_query($con, "UPDATE users SET name='" . $name . "' WHERE id='" . $id . "'"))
{
$successmsg = "Successfully Updated! ";
}
else
{
$errormsg = "Error in Update...Please try again later!";
}
}
}
else
{
$errormsg = "Failed Please Try Again Later !";
}
?>

<div class="collapse navbar-collapse" id="navbar1">
<ul class="nav navbar-nav navbar-right">
<?php if (isset($_SESSION['usr_id'])) { ?>
<li>
<p class="navbar-text">Signed in as <?php echo $_SESSION['usr_name']; ?></p>
<a class="navbar-brand" href="updatephp.php">Update</a>
</li>
<li>
<a href="logout.php">Log Out</a>
</li>
<div style="border:1px dashed transparent;margin-top:400px;position:absolute;margin-left:-35%;">
<h1> Hello User <?php echo $_SESSION['usr_name']; ?> ! </h1>
<h1> Your Email is <?php echo $_SESSION['usr_email']; ?> ! </h1>

<form action="" method="post">
Name: <input type="text" name="name" placeholder="<?php echo $_SESSION['usr_name']; ?>"><br>
<input type="submit" value="Update" name="UpdateUser">
</form>
</div>

<?php } else { ?>
<li><a href="login.php">Login</a></li>
<li><a href="register.php">Sign Up</a></li>
<?php } ?>
</ul>
</div>

Answer

[NOTE: You don't have any textbox named as id.]

Choose any way.

Way 1)

Change

$id = mysqli_real_escape_string($con, $_POST['id']);

To

$id = $_SESSION['usr_id'];

Updated Code:

<?php
if (isset($_POST['UpdateUser'])) {
  $name = mysqli_real_escape_string($con, $_POST['name']);
  $id = $_SESSION['usr_id'];

Way 2)

Add one hidden input field having value session usr_id.

<form action="" method="post">
      Name: <input type="text" name="name" placeholder="<?php echo $_SESSION['usr_name']; ?>"><br>
      <input type='hidden' value="<?php echo $_SESSION['usr_id'];?>" name='id'>
      <input type="submit" value="Update" name="UpdateUser">
</form>

In this way, your submitting form code will be same as you are having.

Comments