php undefined variable while using localhost [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.
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

Related

I want to get output from mcu8266 saved to Mysql via PHP but get an error [duplicate]

This question already has answers here:
How can I get useful error messages in PHP?
(41 answers)
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 1 year ago.
I'm having trouble putting values ​​on my php and sending them to My sql.
<?php
$tempSerialNumber = $_GET['sn'];
$tempLatitude = $_GET['l1'];
$tempLongitude = $_GET['l2'];
$servername = "localhost";
$username = "bornitex_uptoyou";
$password = "12345678";
$dbname = "bornitex_TMS";
$conn = new mysqli($servername, $username,$password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$val1 = $_GET['tempSerialNumber'];
$val2 = $_GET['tempLatitude'];
$val3 = $_GET['tempLongitude'];
$sql = "INSERT INTO LogGPS (SerialNumber, Latitude, Longitude)
VALUES ($val1,$val2,$val3)";
if ($conn->query($sql) === TRUE) {
echo "save OK";
} else {
echo "Error:" . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The value I sent
http://uptoyoutest.bornitexpert.com/add02.php?sn=abc&l1=1.0&l2=2.0
error I got
Error:INSERT INTO LogGPS (SerialNumber, Latitude, Longitude) VALUES (,,)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ',)' at line 2
The database I created
enter image description here

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.

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

I am facing problems in the register 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 5 years ago.
<?php
require('includes/core.inc.php');
require('includes/database/connect.db.php');
session_start();
if(isset($_POST['Register'])) {
$username=$_POST['Username'];
$password=$_POST['Password'];
$query= "INSERT into users (Username,Password) VALUES ('$username','$password')";
$res = mysql_query($query);
if($res){
header("Location:index.php");
}
}
?>
I am facing problems while inserting data in the database don't know why the query is correct this problem is while selecting from database
Notice: Undefined index: Username in C:\xamp\htdocs\chatbox\index.php on line 4
<?php
require('includes/core.inc.php');
session_start();
echo "Welcome".$_SESSION['Username'];
if(isset($_POST['send'])){
if(send_msg($_POST['sender'],$_POST['message'])){
//echo "Message sent ...";
}else{
//echo "failed to sent ";
}
}
?>
try this remember you have to set session variable before using it.
<?php
require('includes/core.inc.php');
require('includes/database/connect.db.php');
session_start();
if(isset($_POST['Register'])) {
$username=$_POST['Username'];
$password=$_POST['Password'];
$_SESSION['Username'] = $username;
$query= "INSERT into users (Username,Password) VALUES ('$username','$password')";
$res = mysql_query($query);
if($res){
header("Location:index.php");
}
}
?>
also to get rid of undefine index issue you should always use
echo "Welcome".isset($_SESSION['Username'])?$_SESSION['Username']:"";
hope your issue will get resolved.

getting notice like undefined index [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.
$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);

Categories