Php – Undefined index: userid

mysqlphp

I'm creating an edit user profile for my project. I came across this error "
Notice: Undefined index: userid in C:\xampp\htdocs\HelloWorld\EditProfile.php on line 18
". I've spent an hour trying to find the cause of the error but I can't seem to find it. I followed this guide here php -'Edit' function for forum posts and such Here's my code:

EditProfile.php

<?php 
// connect to SQL
$dbcnx = mysql_connect("localhost", "root", "2345fypj");
if (!$dbcnx)
  {
  echo( "<P>Unable to connect to the database server at this time.</P>" );
  exit();
}

// connect to database
$dbcon = mysql_select_db("my_db", $dbcnx);
if (!$dbcon) {
  echo( "<P>Unable to locate DB table at this time.</P>" );
  exit();
}

//data preparation for the query
$id = intval($_GET['userid']);

// selects title and description fields from database
$sql = "SELECT * FROM user_profile WHERE userid=$id";
$result = mysql_query($sql) or die(mysql_error());        
# retrieved by using $row['col_name']
$row = mysql_fetch_array($result);

?>

<h3>Edit</h3>
<form action="save_edit.php" enctype="multipart/form-data" method="post" name="myForm" />
  <table>
    <tr>
      <td><b>Name</b></td>
      <td><input type="text" size="70" maxlength="100" name="title" value="<?php echo $row['name'] ?>"></td>
    </tr>
    <tr>
      <td><b>Age</b></td>
      <td><input type="text" size="70" maxlength="100" name="title" value="<?php echo $row['age'] ?>"></td>
    </tr>
  </table>
  <input type="hidden" name="id" value="<?php echo $id; ?>" />
  <input name="enter" type="submit" value="Edit">
</form>

<?php 
mysql_close($dbcnx);
?>

save_edit.php

<?php
// connect to SQL
$con = mysql_connect("localhost", "root", "2345fypj");
if (!$con) {
  echo( "<P>Unable to connect to the database server at this time.</P>" );
  exit();
}
// connect to database
$dbcon = @mysql_select_db("user_profile", $con);
if (!$dbcon) {
  echo( "<P>Unable to locate DB table at this time.</P>" );
  exit();
}

#data preparation for the query
$id = intval($_POST["userid"]);
foreach ($_POST as $key => $value) $_POST[$key] = mysql_real_escape_string($value);

$sql = "UPDATE user_profile SET 
        name='$_POST[name]', 
        age='$_POST[age]', 
        WHERE userid=$id";

if (!mysql_query($sql,$con)) {
  die('Error: ' . mysql_error());
}

mysql_close($con);
header ("location: http://www.domain.com/url_to_go_to_after_update");
?>

Thanks in advance.

Best Solution

$id = intval($_GET['userid']);

It means set the $id variable to the "userid" variable in your URL. For example, if your URL is mySite.com?userid=12, $id will be set to "12". if your URL doesn't have "username=aValue" at the end section of it, you'll get the error you're seeing. :)

You could change it to this to set a default value:

$id = (isset($_GET['userid']) ? intval($_GET['userid']) : -1);
Related Question