php code sends empty data from html field without JavaScript validation

This may sound weird but sometimes when I load the PHP page, it skips validation and enters an empty string from the HTML field into the MYsql database. The javascript alert box after mysql_affected_rows is displayed.

Is there a problem with mysql_affected_rows() ?

<?php
include ("db_connect.inc");

error_reporting(E_ALL ^ E_NOTICE);
error_reporting(E_ERROR | E_PARSE);
$userid= $_REQUEST['id'];
$pass = $_POST['password'];


$query = "UPDATE user SET password = '$pass' WHERE user_id='$userid'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_affected_rows()==1)
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
{
window.alert('Succesfully Updated');
window.location.href='index.php';}
</SCRIPT>");
}



?>

Javascript validation

<script language="javascript">
  function validate()
  {
var str=true;
document.getElementById("msg1").innerHTML="";
document.getElementById("msg2").innerHTML="";
document.getElementById("msg3").innerHTML="";
if(document.frm.userid.value=='')
{ 
document.getElementById("msg1").innerHTML="Please Enter User ID";
str=false;
}

if(document.frm.password.value=='')
{
document.getElementById("msg2").innerHTML="Please Enter Password";
str=false;
}

if(document.frm.password.value!=document.frm.confirm_password.value)   
{
document.getElementById("msg3").innerHTML="Password and Confirm Password         does not match";
str=false;
}


return str;
}
</script>

HTML form

<form name="frm" action="" method="post" >
<table border="1" align="center">
<tr>
<td>User ID</td>
<td>
<input name="userid" type="text" value="<?php print $userid?>">
<div id="msg1" style="color:#FF0000"></div>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input name="password" type="password">
<div id="msg2" style="color:#FF0000"></div>
</td>
</tr>
<tr>
<td>Confirm Password</td>
<td>
<input name="confirm_password" type="password">
<div id="msg3" style="color:#FF0000"></div>
</td>
</tr>
<tr>
<td colspan="2" align="center">
  <input name="btnsubmit" type="submit" value="Submit" onclick="return validate();">
</td>
</tr>
</table>
</form>

Answers


You're probably running your form handling code unconditionally, e.g.

<?php
 .... process form stuff
?>
display form

You need to check if a form was actually submitted, e.g

<?php
if ($_SERVER['REQUEST_METHOD'] == 'post') { 
   ... process form
}
?>
display form

And note that your are vulnerable to sql injection attacks.


Need Your Help

Why primitive arrays are not allowed to add to a JSON structure in GSON

java json gson

I want to do this to create a json object like below.

Take Screenshot of current user control or any GUI in Silverlight 3

c# wpf wcf silverlight silverlight-3.0

I would like to ask if it is possible to take screenshot of current user control programmatically and save as a file in silverlight 3.