getting notice like undefined index [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 8 years ago.
$result = mysql_query("SELECT * FROM customers
WHERE loginid='$_POST[login]' AND accpassword='$_POST[password]'");
if(mysql_num_rows($result) == 1)
{
while($recarr = mysql_fetch_array($result))
{
$_SESSION[customerid] = $recarr[customerid];
$_SESSION[ifsccode] = $recarr[ifsccode];
$_SESSION[customername] = $recarr[firstname]. " ". $recarr[lastname];
$_SESSION[loginid] = $recarr[loginid];
$_SESSION[accstatus] = $recarr[accstatus];
$_SESSION[accopendate] = $recarr[accopendate];
$_SESSION[lastlogin] = $recarr[lastlogin];
}
$_SESSION["loginid"] =$_POST["login"];
header("Location: accountalerts.php");
}
else
{
$logininfo = "Invalid Username or password entered";
}
Notice: Undefined index:login and
Notice: Undefined index:password
try to help me out
getting error message in second line

It seems as if u did not pass the POST params used inside your query:
> $result = mysql_query("SELECT * FROM customers
> WHERE loginid='$_POST[login]' AND accpassword='$_POST[password]'");
You have to send key value pairs explicitly to your script. One for login and one for password.

You need to wrap the index names in quotes, and your query string is hella messy.
$query = sprintf(
"SELECT * FROM customers WHERE loginid='%s' AND accpassword='%s'",
$_POST['login'],
$_POST['password']);
$result = mysql_query($query);
That whole thing should be wrapped in a block like:
if( isset($_POST['login']) && isset($_POST['password']) ) {
//code here
} else {
echo "No username/password supplied.";
}
mysql_* functions are going away, learn to use mySQLi or PDO.
Your query is as wide-open to SQL injection as anything could ever possibly be. Look into parameterized queries with mySQLi or PDO, or at least validating your data before including it in your query.
Here's a PDO example:
//create DB object
$dbh = new PDO('mysql:host=mysql.domain.com;dbname=mydb', $username, $password);
//write query
$query = "SELECT * FROM customers WHERE loginid = ? AND accpassword = ?";
//define parameters to replace ?
$params = array($_POST['login'], $_POST['password']);
//prepare the statement
$sth = $dbh->prepare($query);
//execute
if( ! $sth->execute($params) ) {
//error reporting
die('Query failed: ' var_export($dbh->errorInfo(), true));
}
//fetch all results as associative array
$results = $dbh->fetchAll(PDO::FETCH_ASSOC)l
//display
var_dump($results);

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!!

how to fix undefined variable issue in code while extracting data from database in input field [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 3 years ago.
I am trying to fetch the data from database for a an input field product code and i need to use its value to update the rest of the column values in the database but instead it is creating a different record and in the value field of the input box 'named' code, it shows and undefined variable error, please help.
HTML code:
<div class="small-8 columns">
<input type="text" id="right-label" placeholder="Product_code"
value="<?php echo "$pcode"?>" name="code">
</div>
PHP Script:
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="bolt";
try{
$conn = new
PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["submit"])){
$pcode = ($_POST["code"]);
$pname = ($_POST["Pname"]);
$pdesc = ($_POST["desc"]);
$pimg = $_FILES["Img_name"]["temp_name"];
$imgExt = strtolower(pathinfo($pimg,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg','jpg','png','gif','pdf');
$pqty = ($_POST["Pqty"]);
$pprice = ($_POST["Pprice"]);
$sql="UPDATE products SET product_name=$pname,product_desc=$pdesc,
product_img_name=$pimg,qty=$pqty,price
=$pprice) WHERE product_code=$pcode";
$stmt = $conn->exec($sql);
$stmt->execute();
echo $stmt->rowCount() . "new records added succesfully";
}
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
$sql is declared within the if condition, if if(isset($_POST["submit"])){
is false, you will get this error because $sql is not within the scope. Declare it on above condition and initialize it.

Undefined offset trying to echo data from database [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 am trying to echo out the number of agility that is set in the database. This is my current code, if you could check it out and see if there is anything i need to change to get it working. Currently im getting the error
Notice: Undefined offset: 0 in
$dbserver = "localhost";
$dbusername = "root";
$dbpassword = "*******";
$db = "********";
//CREATE CONNECTION
$conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
$id = $_SESSION['loggedin'];
$query = "SELECT * FROM stats WHERE id='$id'";
$stmt = mysqli_query($conn, $query);
$result = mysqli_fetch_all($stmt,MYSQLI_ASSOC);
<div class="Agility">
<h2>Agility</h2>
<p><?php echo $result[0]['agility']; ?></p>
</div>
First off, since your id field is probably unique, you should limit the query to one. Then, check the number of rows returned by the query before displaying the results in case there are none.
$query = "SELECT * FROM stats WHERE id='$id' LIMIT 1";
$stmt = mysqli_query($conn, $query);
if(mysqli_num_rows($stmt) > 0){
$result = mysqli_fetch_all($stmt,MYSQLI_ASSOC);
?>
<div class="Agility">
<h2>Agility</h2>
<p><?php echo $result[0]['agility']; ?></p>
</div>
<?php } else { ?>
<p>There are no results.</p>
<?php } ?>

PHP ERROR: What is wrong with these php code? It says undefined index error [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.
My code:
$name=$_POST["name"];
This is the error
Notice: Undefined index: name in /home/u615903880/public_html/reg3.php
on line 4
code :
<?php
$con = new mysqli("xxxxx", "xxxx", "xxxx");
$name = $_POST["name"];
$username = $_POST["username"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO users (name, username, emailaddress, password)VALUES (?,?,?,?)");
mysqli_stmt_bind_param($statement, "ssss", $name, $username, $emailaddress, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
mysqli_stmt_close($statement);
mysqli_close($con);
?>
Error lines 4,5,6,9,10,14
Try
$name = isset($_POST['name']) ? $_POST['name'] : 'nothing provided';
You can put anything instead of 'nothing provided' like NULL or something
Its Notice not an error:
you can use
error_reporting(1);
on top of page this will hide warnings and notices.
or you can use code this way
if(isset($_POST["name"])){
$name=$_POST["name"];
}
You didn't send a POST variable called name. If it was from an HTML form, make sure the input is not disabled or it won't post. Also, make sure your form field has a name and not just an id, as it is the name that is used in a post request:
<input type="text" id="notused" name="used" />
In which case $_POST['used'] would work upon submission.
I suspect the key 'name' is not defined in the $_POST array.
to check for missing key you could use:
$name = $_POST["name"]??null; // PHP /7+
or
$name = isset($_POST["name"])?$_POST["name"]:null; // older

php undefined variable while using localhost [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 8 years ago.
Hey i need assistance with this error i am having **Notice: Undefined variable: feedback in C:\xampp\htdocs\ZoomiezWebApp\addNewCustomer.php on line 16** .
I am trying to create a form to add a new customer.
This is the code
<?php
#1> Retrieve Form Details
$fname= $_POST['fname'];
$lname= $_POST['lname'];
$address= $_POST['address'];
$cNumber= $_POST['contactNumber'];
#2 SANITIZE AND VALIDATE DATA
$fname = filter_var($fname, FILTER_SANITIZE_STRING);
$lname = filter_var($lname, FILTER_SANITIZE_STRING);
$address = filter_var($address, FILTER_SANITIZE_STRING);
$cNumber = filter_var($cNumber, FILTER_SANITIZE_STRING);
if($fname==""){//Validate fields for null or empty
***ERROR IS IN THIS LINE***$feedback .= "<br>First Name Field Empty.";
}if($lname==""){
$feedback .= "<br>Last Name Field Empty.";
}if($address==""){
$feedback .= "<br>Address Field Empty.";
}if($cNumber==""){
$feedback .= "<br>Contact Number Field Empty.";
}else{ //Validation Passed...
// #3> CONNECT MYSQL ON THE DB SERVER /
$con = mysql_connect('localhost', "root", "test")
or die ('Could not connect to the database');
// #4> SELECT THE DATABASE ON THE SERVER /
$con = mysql_select_db('zoomiezdb', $con)
or die ('Could not locate database');
// #5> CREATE INSERT QUERY
$addCustomerQuery =
"INSERT INTO customertable (First Name, Last Name, Address, Contact Number) VALUES ('$fname', '$lname', '$address', '$cNumber')) ";
// #6> EXECUTE QUERY
$queryResult = mysql_query($addCustomerQuery);
// #7> VERIFY IF QUERY IS SUCCESSFUL
if($queryResult)
$feedback = "New Customer Added";
else
$feedback = "<i>Add New Customer was Unsuccessful.</i>
<br>
Please Contact Site Administrator...";
// #8> REDIRECT
Header("Location:newCustomer.php?feedbackMsg=$feedback");
}
?>
You should initialize that variable before the conditions if there is no error $feedback never initializes in this case you can initialize it with '' because when you concatenate it PHP doesn't have anything to concatenate

Categories