Undefined Index - PHP MySQL [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
strange php error
Submit an HTML form with empty checkboxes
PHP form checkbox and undefined index
Some reason I am getting undefined index errors in the following code. Any help would be appreciated. Here are the errors I am Recieving
Notice: Undefined index: username in C:\xampp\htdocs\register.php on line 5
Notice: Undefined index: password in C:\xampp\htdocs\register.php on line 6
Notice: Undefined index: firstname in C:\xampp\htdocs\register.php on line 7
Notice: Undefined index: surname in C:\xampp\htdocs\register.php on line 8
Code:
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("clubresults") or die(mysql_error());
$username = $_POST['username'];
$password = md5($_POST['password']);
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$sql = "INSERT INTO members (Username, Password, Firstname, Surname) VALUES ($username, $password, $firstname, $surname);";
mysql_query($sql);
?>
<html>
<div class="content">
<center>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="0">
<tr><td colspan=2><h1>Register</h1></td></tr>
<tr><td>Username:</td><td>
<input type="text" name="username" maxlength="60">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password" maxlength="10">
</td></tr>
<tr><td>Firstname:</td><td>
<input type="text" name="firstname" maxlength=210">
</td></tr>
<tr><td>Surname:</td><td>
<input type="text" name="surname" maxlength=210">
</td></tr>
<tr><th colspan=2><input type="submit" name="submit"
value="Register"> </th></tr> </table>
</form>
</center>
</div>
</html>

When your page loads for the first time (unless it was the action of another page), the REQUEST_METHOD is 'GET'; as a result, no POST variables exist (although the $_POST superglobal exists).
When you POST, either from another page, or from the same page, all the data set in the form will be present in the $_POST superglobal, and can be accessed the way you accessed them earlier; unfortunately, if a data is not present, and you try to access it, an error will be thrown, similar to what you have.
To solve the issue, especially if you want to post to the same page as the form, use something like
if (isset($_POST["username"]))
{
// do whatever
}
if (isset($_POST["password"]))
{
// do whatever
}
if (isset($_POST["firstname"]))
{
// do whatever
}
if (isset($_POST["surname"]))
{
// do whatever
}
With that, your code won't throw an error if those data aren't present.
Hope that helps.
On an unrelated, but important note, do not use mysql_* functions anymore. They have been deprecated; use mysqli or PDO functions for data access.
Happy coding!

Related

undefined index name1 and Undefined index name2

these are the two files in which error is occurred:
html_form.html
<html>
<body>
<center>
<h1>Admission Form</h1>
<br>
<form action="php_register.php" name="registration">
Firstname: <input type="text" name="name1" placeholder="Enter Firstname"/>
<br>
Lastname: <input type="text" name="name2" placeholder="Enter Lastname"/><br>
<input type="submit" value="submit">
</form>
</center>
</body>
</html>
php_register.php
<?php
$fname=$_POST['name1'];
$lname=$_POST['name2'];
$conn=mysqli_connect("localhost","root","","test");
if (isset($fname) && isset($lname))
{
mysqli_query($conn, "insert into test_table(firstname,lastname)
values ('$fname','$lname')");
}
else
echo "<br> Errror....Values are not set in variables...!!!";
?>
( ! ) Notice: Undefined index: name1 in C:\wamp2\www\PHP_project\php_register.php on line 2
Call Stack
Time Memory Function Location
1 0.0022 131712 {main}( ) ...\php_register.php:0
( ! ) Notice: Undefined index: name2 in C:\wamp2\www\PHP_project\php_register.php on line 3
Call Stack
Time Memory Function Location
1 0.0022 131712 {main}( ) ...\php_register.php:0
Errror....Values are not set in variables...!!!
You need to add method="post" to your <form> tag.
Also you could a check if those values are set before on your php_register.php page to ensure the script will run successfully.
e.g.
if (empty($_POST['name1']) || empty($POST['name2']) {
// some kind of error setting and redirecting back maybe
}
By default, form method is GET but you are trying to get values By $_POST.
You didn't define form POST method then you can get values by $_GET or $_REQUEST as:
$_GET['name1'];
$_GET['name2'];
or
$_REQUEST['name1'];
$_REQUEST['name2'];
If you want to use $_POST then you should define form method="post"
If you have no idea about form method, It's a better way to use $_REQUEST. By $_REQUEST you can get both type values.
Example:
$fname=isset($_POST['name1'])?$_POST['name1']:'';
$lname=isset($_POST['name2'])?$_POST['name2']:'';
$conn=mysqli_connect("localhost","root","","test");
if (!empty($fname) && !empty($lname))
{
mysqli_query($conn, "insert into test_table(firstname,lastname)
values ('$fname','$lname')");
}
else
echo "<br> Errror....Values are not set in variables...!!!";
u don't declare POST or GET in the form ,but u use $_POST['name1'] to get the value, thats where the error occured.

trying to make feedback page [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
I am making feedback page, but it is producing some errors.
i don't understand what is wrong. Please help me figure out where i am doing wrong.
when i submit the form the errors goes away and produce right result,but when i refresh the page it produces same errors again
<?php
$name = $_POST['name']; // error undefined index name
$suggestion = $_POST['suggest']; // error undefined index suggest
$opinion = $_POST['opinion']; // error undefined index opinion
$submit = $_POST['submit']; // error undefined index submit
if(isset($submit)){
$sql= mysqli_query($con,"insert into feedback (name,suggestion,opinion) values ('$name','$suggestion','$opinion')");
if($sql==true){?>
<div class="alert alert-info">
Thankyou for your suggestions. we will notify the admins.
</div>
<?php
}
}
?>
<body>
<div class="feedback">
<form action="feedback.php" method="post">
<h1> Help us improve our website</h1>
<h2>Please drop your suggestion below</h2>
<div class="form-group">
<label >Your Name:</label>
<input type="text" class="form-control" name="name" required>
</div>
<div class="form-group">
<label for="comment">Your suggestion</label>
<textarea class="form-control" name="suggest" rows="5" id="comment" required ></textarea>
</div>
<p>Were you satisfy with this website?</p>
<label class="checkbox-inline">
<input type="checkbox" name="opinion"value="1"> yes
</label>
<label class="checkbox-inline">
<input type="checkbox" name="opinion" value="2"> no
</label>
<label class="checkbox-inline">
<input type="checkbox" name="opinion" value="3"> may be
</label>
<br /><br />
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
When initially rendering the page, it's unable to locate the index (ie. value) for $_POST array (name, suggest, etc.). That's because there is no $_POST data until you submit the form. When you submit the form, $_POST contains data, including those indexes, so it's able to successfully render the page.
You should check to see if the variable has been set or not. Something along these lines will do that:
if (isset($_POST["name"]) {
$name = $_POST["name"];
}
You can do this for each variable.
I also recommend including that within the submit condition, as it should only check for that data if the form was submitted.
Additionally, you should look into using prepared statements or input sanitization as you are setting yourself up for SQL Injection with the mysqli query.
That's because parameters passed with post method are related only to a specific page request. When you refresh the page, browsers usually ask you if you want to send forms again, otherwise the request is sent without additional data.
Your issue is exactly what the error states, your $_POST array is empty when the page is first loaded, and it is not empty (so you do not get the error) when you have POSTED the form.
replace your variable declarations as follows to make sure they are properly declared incase the $_POST array is empty:
$name = isset($_POST['name']) ? $_POST['name'] : "";
$suggestion = isset($_POST['suggest']) ? $_POST['suggest'] : "";
$opinion = isset($_POST['opinion']) ? $_POST['opinion'] : "";
$submit = isset($_POST['submit']) ? $_POST['submit'] : "";
if(isset($submit) && $submit != ""){
// your insert code here
}

$_POST not working in a login form [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
I've spent hours over this code (i'm a php newbie) but I just can't figure out why it doesn't work.
I have 2 webpages: the main one, and the login handler.
The login one should take the values I put in the login form (placed in the main page) and then execute operations such as checking whether the user exists or not, whether he is an admin or not and whatsoever.
Turns out the starting postgres query is wrong for some reasons -or maybe I should say the values taken from the form are not recognized correctly -, even though I tried to use it on another test.php page using actual values instead of the $_POST variables and it worked flawlessly
MainPage
<?php
ini_set ("display_errors", "1");
error_reporting(E_ALL);
$host = "host=127.0.0.1";
$port = "port=5432";
$dbname = "dbname=Library";
$credentials = "user=john password=doe";
$db = pg_connect( "$host $port $dbname $credentials" ) or die('Could not connect');
?>
<title>Welcome</title>
<head><font size="16" color="black">Library</font></head>
<br />
<br />
<br />
<body>
<form action="LoginHandler.php" method="POST">
ID:<input type="string" name="UserID">
Password:<input type="string" name="Password">
<input type="submit" value="Login">
</form>
<form action="createUser.html" method="get">
<input type="submit" value="Sign Up"><br>
</body>
LoginHandler
<?php
$UserID=$_POST["UserID"];
$Password=$_POST["Password"];
$user=pg_query($db, "SELECT UserID, Password, Privileges
FROM Library.Users
WHERE UserID='$UserID' AND Password='$Password'");
$val = pg_fetch_result($user, 0, 0);
echo $val;
?>
I just tried the code on a text page again so I'm 100% sure the query is correct.
Any suggestions?
my friend there couple of issues here can blow up ur code
1- the form html code is missed up.it should look like that:
<form action="LoginHandler.php" method="POST">
ID:<input type="text" name="UserID">
Password:<input type="password" name="Password">
<input type="submit" value="Login">
</form>
<form action="createUser.html" method="get">
<input type="submit" value="Sign Up"><br>
</form>
2- you should learn the difference between using single quote and double quote , they are not the same in PHP
so your query should look like that
$user=pg_query($db, 'SELECT UserID, Password, Privileges
FROM Library.Users
WHERE UserID="$UserID" AND Password="$Password"');
3- i want to tell u that this code can work for practicing or testing but it is not a real world code , u should hash the password
use $password = sha1($password); at least, also u should filter the $_POST and $_GET inputs using htmlspecialchars() and filter_var(), check the php manual for best explanation for this functions.

Undefined variable: ... in ...on line 9

I'm trying to make a form that updates a datebase but it gives me two errors. Do you have any idea what it could be from?
The errors:
Notice: Undefined variable: Points inD:\2013.1\xampp\htdocs\ranklist_get.php on line 9
Notice: Undefined variable: Skype in D:\2013.1\xampp\htdocs\ranklist_get.php on line 9
welcome.html
<body>
<form action="ranklist_get.php" method="get">
Skype: <input type="text" id="Skype"><br>
Points: <input type="number" id="Points"><br>
<input type="submit">
</form>
</body>
</html>
ranklist_get.php
<?php
$con=mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"UPDATE Persons SET Points='".$Points."' WHERE Skype='".$Skype."'");
mysqli_close($con);
?>
Initialize your variables with the expected values before you use them in your query.
$Points=mysqli_real_escape_string($con,$_GET["Points"]);
$Skype=mysqli_real_escape_string($con,$_GET["Skype"]);
Also make sure to add the name attribute to your form fields. name="Points" and name="Skype", otherwise it wont work.
GET variables are stored in the global $_GET array (just like POST and COOKIE). You can either use them directly in your code like so $_GET["Points"] or store them in a variable.
Please note you should use the name property on each input to specify it's key in the array.
At the top of your code put:
$Points = $_GET["Points"];
$Skype = $_GET["Skype"];
Your form should be rewritten like so:
<form action="ranklist_get.php" method="get">
Skype: <input type="text" id="Skype" name="Skype"><br>
Points: <input type="number" id="Points" name="Points"><br>
<input type="submit">
</form>
You should also sanitize your MySQL query like so:
$query = mysqli->prepare($con, "UPDATE Persons SET Points=? WHERE Skype=?");
$query->bind_param('ss', $points, $skype);
$points = $_GET["Points"];
$skype = $_GET["Skype"];
$query->execute();
You can read more about prepared statements here: http://php.net/manual/en/mysqli.prepare.php
make HTML as
<html>
<body>
<form action="ranklist_get.php" method="get">
Skype: <input type="text" id="Skype" name="Skype"><br>
Points: <input type="number" id="Points" name="Points"><br>
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>
ranklist_get.php
<?php
$con=mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if($_REQUEST['Submit']=='Submit'){
$Points=$_REQUEST['Points'];
$Skype=$_REQUEST['Skype'];
mysqli_query($con,"UPDATE Persons SET Points='".$Points."' WHERE Skype='".$Skype."'");
}
mysqli_close($con);
?>
You have to get the values before you use it.

mysql UPDATE variable

Hi guys i have code like this
include('db.php');
if (isset($_POST['save']) && $_POST['save'] == '') {
if(isset($_POST['misamarti'])){ $misamarti = $_POST['misamarti']; }
if(isset($_POST['teleponi'])) { $teleponi = $_POST['teleponi']; }
if(isset($_POST['posta'])) { $posta = $_POST['posta']; }
if(isset($_POST['paqsi'])) { $paqsi = $_POST['paqsi'];}
$query = "UPDATE contact SET `misamarti` = ".$misamarti.", `teleponi` = ".$teleponi.", `posta` = ".$posta.", `paqsi` = ".$paqsi." WHERE `contact`.`id` =1;";
$result = mysql_query($query);
}
<form method="post" action="" enctype="multipart/form-data">
<input type="hidden" name="about" value="template1" />
<input type="text" value="" name"misamarti" />
<input type="text" value="" name"teleponi" />
<input type="text" value="" name"posta" />
<input type="text" value="" name"paqsi" />
<input type="submit" value="" name="save" />
and result is
Notice: Undefined variable: misamarti in C:\xampp\htdocs\Template\admin_panel\contact.php on line 18
Notice: Undefined variable: teleponi in C:\xampp\htdocs\Template\admin_panel\contact.php on line 18
Notice: Undefined variable: posta in C:\xampp\htdocs\Template\admin_panel\contact.php on line 18
Notice: Undefined variable: paqsi in C:\xampp\htdocs\Template\admin_panel\contact.php on line 18
if anyone know why is this error pls comment.
You're using the variables even if they weren't submitted with the form, and update the fields in the db with those undefined varaibles, so you'll be destroying any data that was in the DB previously.
If nothing else, you need to at least set a default value for the fields, e.g:
$misamarti = isset($_POST['misamarti']) ? $_POST['misamarti'] : '';
^^--default empty string
And then realize that you are WIDE OPEN to an sql injection attack. You are BEGGING to get your server pwn3d.
As you can see in your HTML code, you have the names bad written, they have to be written this way: name="misamarti". You forgot the equal (=) between name and the name. If you see the rest of attributes, like text and value, you see that theres an equal, that's the correct way of setting attributes.

Categories