Unable to update my userdetails table in MysSQL

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jagannathg
Forum Commoner
Posts: 34
Joined: Wed Dec 08, 2010 1:55 am

Unable to update my userdetails table in MysSQL

Post by jagannathg »

Hello All,

I have come back again to DevNetwork Forum for my rescue. I have a login Page which works fine and takes the users to the members page. In the members page I have given a option to the users to edit there profile. There are only two fields that they need to edit one is Email and second one is Location.

Now my questions are how to go about it. I have my members page code below which the user gets access to once they login:

Code: Select all

<?php

session_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="rajeshwari"; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$username = $_POST['username'];
$password = $_POST['password'];


if ($username&&$password)
{

$connect = mysql_connect("localhost","root","rajeshwari") or die ("Couldn't connect!");
mysql_select_db("test") or die ("Couldn't find db");

$query = mysql_query("SELECT * FROM userdetails WHERE username='$username'");

$numrows = mysql_num_rows($query);

if ($numrows!=0)
{

   while ($row = mysql_fetch_assoc($query))
   {
         $dbusername = $row['username'];
         $dbpassword = $row['password'];

   }

   // check to see if they match!
   if ($username==$dbusername&&$password==$dbpassword)
   {
       //$row = mysql_fetch_array($result, MYSQL_ASSOC);
       //echo "{$row['firstname']}";
       $_SESSION['username']=$dbusername;
       echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
       echo "<b>You are logged in as:</b>&nbsp;&nbsp;&nbsp;<b>".$_SESSION['username']."</b>&nbsp;&nbsp;&nbsp;&nbsp;<a href='logout2.php'>[Logout]</a>";

       $dt1 = time();
       $dt2 = time();
       $mysql_datetime1 = strftime("%d %B %Y", $dt1);
       $mysql_datetime2 = strftime("%H:%M %p", $dt2);
       echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
       echo "<b>Current Login Date: $mysql_datetime1</b>";
       echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
       echo "<b>$mysql_datetime2</b>";
   }
   else
        die ("Incorrect password!");

}

else
   die("That user doesn't exist!");

}
else
    die ("Please enter username and password");


?>


<head>




	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

	<title>Sanskar - Life with a difference</title>
	<link rel="stylesheet" href="style.css" type="text/css" charset="utf-8" />

</head>

<body>


<div id="outer">
	<div id="wrapper">
		<div id="nav">

		<div id="nav-left">
		    <div id="nav-right">
    			<ul>
                          <li><a href="editprofile.php">Edit Profile</a></li>
    			  <li><a href="http://www.freewebsitetemplates.com">PRODUCTS</a></li>
    			  <li><a href="http://www.freewebsitetemplates.com">SERVICES</a></li>
    			  <li><a href="http://www.freewebsitetemplates.com">SHOPPING CART</a></li>
    			  <li><a href="http://www.freewebsitetemplates.com">NEW GADGETS</a></li>
    			  <li><a href="http://www.freewebsitetemplates.com">REGISTER</a></li>
    			</ul>
		    </div>
		  </div>


		  	<div class="clear"></div>
		</div>
		<div id="head">


			<div id="head-left"></div>
			<div id="head-right"></div>
			<div id="head-1"></div>

			<?php

		              $q = mysql_query("SELECT * FROM userdetails WHERE username='$username'");
                              $rows = mysql_num_rows($q);
                              while($rows = mysql_fetch_array($q))
                              {
                                 echo "WELCOME&nbsp&nbsp";
                                 echo $rows['firstname'];
                                 echo "&nbsp;!!";
                                 echo "&nbsp;&nbsp;";
                                 echo "YOUR ACCOUNT DETAILS:";
                                 echo "<br />";
                                 echo "<br />";
                                 echo "First Name:&nbsp&nbsp&nbsp";
                                 echo $rows['firstname'];
                                 echo "<br />";
                                 echo "Last Name:&nbsp&nbsp&nbsp";
                                 echo $rows['lastname'];
                                 echo "<br />";
                                 echo "Username:&nbsp&nbsp&nbsp";
                                 echo $rows['username'];
                                 echo "<br />";
                                 //echo "Password:&nbsp&nbsp&nbsp";
                                 //echo $rows['password'];
                                 //echo "<br />";
                                 echo "Email Id:&nbsp&nbsp&nbsp";
                                 echo $rows['email'];
                                 echo "<br />";
                                 echo "Location:&nbsp&nbsp&nbsp";
                                 echo $rows['location'];
                             }
                         ?>


		</div>
		<div id="head-2"></div>

</body>
</html>

The below code is for the editprofile.php when the user clicks on the Edit Profile Hyperlink in the above code in member page:

Code: Select all


<?php

session_start();
$id=$_GET['id'];
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="rajeshwari"; // Mysql password
$db_name="test"; // Database name
$tbl_name="userdetails"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$username = $_POST['username'];
$get_memberdetails_sql = "SELECT * FROM $tbl_name WHERE username = '$username'";
$result = mysql_query($get_memberdetails_sql);
$get_memberdetails_res = mysql_fetch_array($result);

$email = $get_memberdetails_res['email'];
$location = $get_memberdetails_res['location'];

?>

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

	<title>Sanskar - Life with a difference</title>
	<link rel="stylesheet" href="style.css" type="text/css" charset="utf-8" />

<script language = "Javascript">

function Validate()
{
    if (document.form1.firstname.value == '')
    {
        alert('Please fill in your first name');
        return false;
    }

    if (document.form1.lastname.value == '')
    {
        alert('Please fill in your last name');
        return false;
    }

    if (document.form1.username.value == '')
    {
        alert('Please fill in your desired username');
        return false;
    }
        if (document.form1.password.value == '')
    {
       alert('Please fill in your desired password!');
      return false;
    }
    if (document.form1.cpassword.value == '')
    {
       alert('Please fill in your password again for confirmation!');
      return false;
    }
    if (document.form1.password.value != document.form1.cpassword.value)
    {
        alert("The two passwords are not identical! "+
        "Please enter the same password again for confirmation");
        return false;
    }
    if (document.form1.email.value == '')
    {
        alert('Please fill in your Email Address');
        return false;
    }
    if (document.form1.location.value == '')
    {
        alert('Please fill in your Email Address');
        return false;
    }
    return true;
}
</script>
</head>


</head>

<body>



<div id="outer">
	<div id="wrapper">
		<div id="nav">

		 <div class="clear"></div>
		</div>
		<div id="head">
			<div id="head-left"></div>
			<div id="head-right"></div>
			<div id="head-1"></div>
			<h1><span class="logo"><span class="top">Sanskar</span><span class="gadgets">life with a difference</span></span></h1>

		</div>
		<div id="head-2"></div>
		<div id="login">
			<div id="login-bot">
				<div id="login-box">
                                <?php
				      echo $_SESSION['username'];
                                ?>
					<h2 class="login"><em>User</em>&nbsp;Update Page</h2>
			<form name='form1' method="post" action="update_ac.php" onsubmit="return Validate();">
						<div id="login-username">

							<div><label for="email">Email</label>: <input type="text" name="email" id="email" value="<?php echo $email;?>"></div>
							<div><label for="location">Location</label>: <input type="text" name="location" id="location" value="<?php echo $location;?>"></div>
						</div>

						<div class="clear">

						<div id="login-button">
							<input type="image" src="images/btn_login.gif" name="l" value="h"/>
						</div>
						</div>
					</form>
				</div>
				<div id="login-welcome">
					<div>
						<h2>Welcome</h2>
						<p>Don't forget to check <a href="http://www.freewebsitetemplates.com">free website templates</a> every day, because we add  a new free website template almost daily.</p>
					</div>
				</div>
				<div class="clear"></div>
			</div>
		</div>

</body>
</html>
My coding is not so effective I know that I have told from an expert in this forum that I should not use &nbsp; which is again a bad practise, but I have used it. I would appricate any help with the above codes where user's can edit there own profile by loging in.

Regards,
Jagannath
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Unable to update my userdetails table in MysSQL

Post by social_experiment »

Your update page needs a way of identifying the user in the database. I found that using the primary key field is easiest, 1, it's auto incrementing and 2, for each record it is unique. Your form's "action" attribute needs to reflect this value action="update_ac.php?id="' . $userID . '". When the page is clicked, the page that displays (update_ac.php) has the following query string "?id=5" (assume the value is 5). Now you use $_GET['id'] to access this value and with that you update the record.

Code: Select all

<?php "UPDATE table SET field1 = value1, field2 = value2 WHERE id = $_GET['id']"; ?>
There are obviously security issues to look at when working with $_GET like checking that the value is set, checking that the value you use is indeed of the type you want (integer in this case).
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
jagannathg
Forum Commoner
Posts: 34
Joined: Wed Dec 08, 2010 1:55 am

Re: Unable to update my userdetails table in MysSQL

Post by jagannathg »

social_experiment wrote:Your update page needs a way of identifying the user in the database. I found that using the primary key field is easiest, 1, it's auto incrementing and 2, for each record it is unique. Your form's "action" attribute needs to reflect this value action="update_ac.php?id="' . $userID . '". When the page is clicked, the page that displays (update_ac.php) has the following query string "?id=5" (assume the value is 5). Now you use $_GET['id'] to access this value and with that you update the record.

Code: Select all

<?php "UPDATE table SET field1 = value1, field2 = value2 WHERE id = $_GET['id']"; ?>
There are obviously security issues to look at when working with $_GET like checking that the value is set, checking that the value you use is indeed of the type you want (integer in this case).
Hello social_experiment,

Looks like everything is working fine and great. Now the users are able to update there details. Thanks for the guidance for using the $_GET (GET Method), but I feel its not secure to pass critical info like username or password as a matter of fact the id can also be gussed if we pass it through GET Method. Any solution for this?

Thanks for your help again!!

Regards,
Jagannath
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Unable to update my userdetails table in MysSQL

Post by social_experiment »

jagannathg wrote:but I feel its not secure to pass critical info like username or password as a matter of fact the id can also be gussed if we pass it through GET Method. Any solution for this?
Your intuition is spot-on. You can pass information using $_POST as well, or session variables. Yes, passing something like an id from page to page is risky and there are some checks you should perform to see if the value that you have retrieved is indeed a useable, non-injection value. Below a simle example that's effective IMO.

Code: Select all

<?php
 // assume we are looking for a numerical value
 $id = trim($_GET['id']);
 // remove any whitespace
 if ($id == '' || !is_numeric($id)) {
 // someone might be messing around
  echo 'Invalid id';
  }
  else {
  // here the id contains a value AND it's numeric
  // now you can simply do a count to see if it is
  // inside the database
  $count = mysql_query("SELECT COUNT(id) FROM table 
  where id = '". mysql_real_escape_string($id) ."' ");

  $array = mysql_fetch_array($count);

  $rows = $array[0];

  // now check if the value is in the database
  if ($rows != 1) {
  // invalid row, do something
  }
  else {
   // continue with your script as the id value 
   // is valid
  }
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
jagannathg
Forum Commoner
Posts: 34
Joined: Wed Dec 08, 2010 1:55 am

Re: Unable to update my userdetails table in MysSQL

Post by jagannathg »

social_experiment wrote:
jagannathg wrote:but I feel its not secure to pass critical info like username or password as a matter of fact the id can also be gussed if we pass it through GET Method. Any solution for this?
Your intuition is spot-on. You can pass information using $_POST as well, or session variables. Yes, passing something like an id from page to page is risky and there are some checks you should perform to see if the value that you have retrieved is indeed a useable, non-injection value. Below a simle example that's effective IMO.

Code: Select all

<?php
 // assume we are looking for a numerical value
 $id = trim($_GET['id']);
 // remove any whitespace
 if ($id == '' || !is_numeric($id)) {
 // someone might be messing around
  echo 'Invalid id';
  }
  else {
  // here the id contains a value AND it's numeric
  // now you can simply do a count to see if it is
  // inside the database
  $count = mysql_query("SELECT COUNT(id) FROM table 
  where id = '". mysql_real_escape_string($id) ."' ");

  $array = mysql_fetch_array($count);

  $rows = $array[0];

  // now check if the value is in the database
  if ($rows != 1) {
  // invalid row, do something
  }
  else {
   // continue with your script as the id value 
   // is valid
  }
?>
Hello social_experiment ,

Thanks for your time and letting me know that we can pass the values using the $_POST or Session Variable. I am surely impliment and check both the things:

1. The $_POST or Session Variable to pass information like id or username.
2. Perform a check to see if the value (id) that I have retrieved is indeed a useable, non-injection value.

Thanks for the code I will perform both these and post it back to you with my results.

Thanks
Jagannath
Post Reply