PHP Notice: Undefined index: username [duplicate] - php

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 getting this kind of error message, any idea what is wrong with the code on line 9? Basically, the code is to search the user input from the form, then search the username from ldap.
PHP Notice: Undefined index: username in C:\inetpub\wwwroot\LDAP\New3\search2.php on line 9
<?php
$ds = #ldap_connect("ldap.xxxxx.my");
if (!$ds) {
die("Unable to connect to test server.");
}
$res = #ldap_bind($ds); # Anonymous bind
$userid = $_POST['username']; // User key their userid or email
$srch = #ldap_search($ds,
"o=company, o=CompanyNet",
"uid=$userid", # Search on username
array('uid'), # We want username
0, # We want values and types (see docs)
10 # We want, at most, 10 results
);
if (ldap_errno($ds) == 4) { # Error code for "too many results"
print "<B>More than 10 results were returned. Only 10 displayed.</B><BR>\n";
}
if ($srch) {
$results = #ldap_get_entries($ds, $srch); # Retrieve all results
for ($i = 0; $i < $results["count"]; $i++) { # Iterate over all results
print "<B>".$results[$i]["uid"][0]."</B> exist in directory "."<BR>\n";
}
}
else {
print "<B>Directory lookup failed: ".ldap_error($ds)."</B><BR>\n";
}
#ldap_close($ds); # Close off my connection
?>
<html>
<head>
</head>
<body>
<form action="search.php" method="POST">
<input type="text" name="username" length="30">
<input type="submit" name="submit" value = "Search">
</form>
</body>
</html>

You're getting the error because you're expecting the $_POST array to be set whenever you load the page.
That is not the case. It will only ever be set when the form is submitted, so you can handle that by adding this if condition:
if(isset($_POST['submit'])) {
$ds = #ldap_connect("ldap.xxxxx.my");
if (!$ds) {
die("Unable to connect to test server.");
}
$res = #ldap_bind($ds); # Anonymous bind
$userid = (!empty($_POST['username'])) ? $_POST['username'] : ''; // User key their userid or email
// ... the rest of your code
}
As Fred stated in the comments, you might want to make sure that username is not empty, by using php's inbuilt function - empty()

Related

Undefined index IN PHP SESSION? [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)
The 3 different equals
(5 answers)
Closed 2 years ago.
I have this code in my login.hmtl in s section with ajax method:
$.ajax ({
type:'post',
url:'Controladores/login.php',
data:{do_login:"do_login", nick:nick, pass:pass },
success:function(response) {
alert($.trim(response));
if ($.trim(response) ==='Correcto'){
window.location.href="intranet.php?ruta=inicio";
return false;
}
else{
alert('Datos incorrectos. Volver a intentar.');
}
}
});
This redirects me to login.php where I connect to the database and then check if the username and password are correct. If they are, they return an answer Correct or Incorrect.
Here is the main part where I start my session, and also if username and password match, set the username 'NICK' to the session.
session_start();
$db = new Conexion();
$conn = $db->connect( '00.00.00.00', 'Seguridad');
$param = [$nick, $pass];
$query = "exec Seguridad.dbo.autenticacion ?, ?";
$result= $db->rows($conn, $query, $param);
$obj = json_decode($result);
//echo $obj[0]->resultado;
if( $obj[0]->resultado ='Correcto' ){
$_SESSION['nick']= $nick;
$_SESSION['nombreusuario'] = $obj[0]->nombreusuario;
$_SESSION['agencia'] = $obj[0]->CodigoAgencia;
echo ("Correcto");
}else{
if ($obj[0]->resultado =='Incorrecto'){
echo ("Incorrecto");
}
}
Then, In my home page called inicio.php I called again the session but the message is:
Notice: Undefined index: nick in C:\xampp\htdocs\intranetv3\Vistas\modulos\inicio.php on line 3
<?php
session_start();
$userName = $_SESSION['nick'];
echo "$userName";
?>
I have read other article but have not found anything.
I checked if the answer Correct or Incorrect returns the answer and it returns.
I printed the user name and password. It worked.
I also printed the $_SESSION['nick'], I see it has the username.
Apparently when I go to my inicio.hmtl the session just unssets or something, I have no idea what might be wrong. Please HELP!!

Notice: Undefined index: namaunit [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 5 years ago.
I'm new in programming, and i don't know why it doesn't work. I use the same code for my other input form, and that code work just fine. But, for this form, it's not. The form is pretty much same, so, that's why i totally do not understand why it's not working.
This is the php code where the message error come from. I wish you can help me. Thank you so much.
<?php
session_start();
require 'db.php';
$kodeunit = $_SESSION["KodeUnit"];
$namaunit = $_POST['namaunit'];
$alamat = $_POST['alamat'];
$pimpinanunit = $_POST['pimpinanunit'];
$kuasaanggaran = $_POST['kuasaanggaran'];
$pembuatkomitmen = $_POST['pembuatkomitmen'];
$penanggungjawab = $_POST['penanggungjawab'];
$sql = "UPDATE unit_organisasi SET Nama_Unit = '$namaunit', Pimpinan_Unit = '$pimpinanunit', Alamat = '$alamat', Kuasa_Anggaran = '$kuasaanggaran', Pembuat_Komitment = '$pembuatkomitmen', Penanggungjawab = '$penanggungjawab' WHERE Kode_Unit = '$kodeunit'";
if((!strlen(trim($namaunit))) || (!strlen(trim($alamat))) || (!strlen(trim($pimpinanunit))) || (!strlen(trim($kuasaanggaran))) || (!strlen(trim($pembuatkomitmen))) || (!strlen(trim($penanggungjawab)))){
echo "<script>alert('Data Belum Lengkap!')</script>";
header ('Location:inpudataunit.php');
}
else{
$result = $conn->query($sql);
if($result === TRUE){
echo "Berhasil diinput";
}
}
?>
Seems like your form has no input field named namaunit . Check your form input name.

Undefined Variable PHP + MySQL [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 know stackoverflow disapproves of repeat questions, but bear with me as I have scanned many similar questions without finding specific resolutions that will help me. (Mostly they mention things about avoiding database insertions)
I encounter these error messages:
here db connection success
Notice: Undefined variable: firstname in C:\xampp\htdocs\practice_connection_app\submit.php on line 10
Notice: Undefined variable: lastname in C:\xampp\htdocs\practice_connection_app\submit.php on line 10
Notice: Undefined variable: conn in C:\xampp\htdocs\practice_connection_app\submit.php on line 11
Fatal error: Call to a member function exec() on null in C:\xampp\htdocs\practice_connection_app\submit.php on line 11
The first result simply shows that I have connected to my database which I made using phpMyadmin.
Here is my relevant code (my html submission page which calls on a php action):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>student info</title>
</head>
<body>
<br>
Enter your first name and last name in the corresponding boxes.
<br>
<form action="submit.php" method="POST">
First: <input type="text" name="firstname"/>
<br>
Last: <input type="text" name="lastname"/>
<br>
<input type="submit">
</form>
</body>
</html>
the database connection (I think)
<?php
echo 'here';
$dsn = 'mysql:host=localhost;dbname=practice_students';
$username = 'test_usr';
$password = 'pa55word';
try {
$db = new PDO($dsn, $username, $password);
echo 'db connection success';
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
?>
AND my php submit page
<?php
echo 'here ';
$dsn = 'mysql:host=localhost;dbname=practice_students';
try {
$db = new PDO($dsn);
echo 'db connection success';
$sql = "INSERT INTO people (firstname, lastname)
VALUES ('$firstname', '$lastname')";
$conn->exec($sql);
echo "Now we know your name! Hi," . " " . $firstname . " " . $lastname;
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
?>
I understand that I may need to do some 'cleaning up' to avoid database insertions, but for now I would just like to know how I can ensure my submissions are going to the database and can be returned.
Thanks in advance!
Not sure which manual you ahve been reading to end up with that code....
You need to access your POST variables (using $_POST['firstname']) AFTER sanitizing them of course....
EDIT:
To access the POSTed variable, you can do the following:
$firstname = $_POST['firstname'];
But you really need some santization going on, you could use php's filter_var:
$firstname = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
Though, you can do better than that, and be very strict in what you allow through your filters / sanitizers... Please go investigate this part after you get your code "working" :)

How do I solve the "Undefined variable" error on php [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.
login.php
<?php
function login()
{
$con = mysqli_connect("localhost", "XXX", "XXX") or die('Could not connect to server');
mysqli_select_db('$con', "store") or die('Could not connect to database');
}
?>
validate.php
Line 10 - ERROR - Notice: Undefined variable: con in C:\wamp\www\store\admin\validate.php
Line 10 - Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\wamp\www\store\admin\validate.php
Line 12 - Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\wamp\www\store\admin\validate.php
<?php
session_start();
include ("../mylibrary/login.php");
login();
$userid = $_POST['userid'];
$password = $_POST['password'];
$query = "SELECT userid, name from admins where userid = '$userid' and password = PASSWORD('$password')";
$result = mysqli_query($con, $query); (**Line 10)
if (mysqli_num_rows($result) == 0)(**Line 12)
{
echo "<h5>Sorry, your account was not validated.</h5><br>\n";
echo "Try again<br>\n";
} else
{
$_SESSION['store_admin'] = $userid;
header("Location: admin.php");
}
?>
I tried to figure out something wrong. Let me know thanks.
See this
mysqli_select_db('$con'
^ ^
Variable don't get parsed in single quotes.
Either remove them or use double " quotes.
Note: Make sure that all your POST arrays contain values and that the form you're using is indeed using a POST method and elements hold their respective name attributes.
You're also open to an SQL injection here.
Use a prepared statement.
References:
https://en.wikipedia.org/wiki/SQL_injection
https://en.wikipedia.org/wiki/Prepared_statement
Also consider using password_hash() to store your passwords:
http://php.net/manual/en/function.password-hash.php (Read the entire manual).
You are mixing up local and global variables.
$con is not available outside the login function.
If you add global $con; as the first line of the login function, its available outside of the function as well.
Have a look at the php manual: http://php.net/manual/en/language.variables.scope.php
PS: While its not the source of the problem, read Fred's answer too.

Call PHP function from html form with parameters [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 am trying to run a simple select on the DB from a HTML form
HTML snippet is
<form Name ="form1" Method ="post" ACTION = "get341Usage.php">
<input type="submit" name="Submit1" value="3 Months" >
</form>
PHP file get341Usage.php
<?php
function get341Usage($org_id,$usage_mnth ) {
$conn = oci_connect('user', 'pass', '//server/ora_instance');
$query = "SELECT usage.* from usage_table usage
where customer_number = ' . $cust_id . '
AND usage_date >= (select add_months(sysdate ,' . $usage_mnth . '))";
$stid = oci_parse($conn, $qryStr);
oci_execute($stid);
oci_free_statement($stid);
}
if(isset($_POST['submit']))
{
getUsage($org_id,$usage_mnth);
}
?>
the reason for the 2 paramters was I wanted to create 3 buttons 3,6,12 monnths where the user to clicks and it prompts to auto save teh data to a csv file (haven't even got to this pary yet!)
any points would be great ...I suspect I'm miles off
if(isset($_POST['Submit1']))
{
getUsage($org_id,$usage_mnth);
}

Categories