Solved

Notice: Undefined variable

Posted on 2016-10-18
5
54 Views
Last Modified: 2016-10-18
Hi All,

I'm getting the following Notice in my php output: -

Notice: Undefined variable: error in /var/www/html/inventoryupdate.php on line 133

Notice: Undefined variable: message in /var/www/html/inventoryupdate.php on line 139

The code that this relates to is as follows: -

<?php
			
				    if ($error) {
			
					   echo '<div class="alert alert-danger">'.addslashes($error).'</div>';
			
					   }
			
				    if ($message) {
			
					   echo '<div class="alert alert-success">'.addslashes($message).'</div>';
			
					   }
			
				    ?>

Open in new window


If you ignore it the output of the php for $error and $message variables work when the form is used accordingly based on the following php which is linked via an include_once statement.

if (isset($_POST['submit'])) {
            
            if (empty($_POST['partID'])) $error.="<br />Please enter the PartID, used by the AssemblyID for deduction.";
            if (empty($_POST['partDescription'])) $error.="<br />Please enter a valid Part Description.";
            if (empty($_POST['qtyInStock'])) $error.="<br />Please enter the initial Stock Qty, usually set to Zero/0.";
            if (empty($_POST['supplierCompany'])) $error.="<br />Please enter the Supplier Company details.";
            if (empty($_POST['supplierCode'])) $error.="<br />Please enter the Supplier Code.";
            if (empty($_POST['supplierDesc'])) $error.="<br />Please enter the Supplier Description.";
            if (empty($_POST['itemCost'])) $error.="<br />Please enter the unit item cost (£).";
            if (empty($_POST['cartonSize'])) $error.="<br />Please enter the carton size.";
            if ($error) $error = "There were error(s) in your entry details, detailed below:".$error;

Open in new window


Thanks J
0
Comment
Question by:Ridgejp
  • 2
  • 2
5 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41848112
Notice: Undefined variable: error in /var/www/html/inventoryupdate.php on line 133
And the code you have shown us has $error on line 3 - so we cannot possibly tell you what the problem is as you have not given us all the pieces.

First rule: the compiler is never wrong. If the compiler says the variable is not defined then it is not defined. Chances are you have a number of code paths through your script and in one of them you are using the value $error where it has not been set yet.

This is the sort of problem

if ($value == 1) 
{
    $error = "Fail";
}

if ($error) {
   // Do something
}

Open in new window

In the above if $value <> 1 then you will get the error you are seeing.

To fix this the correct way of doing the above code is
// Define $error before any block of code that might alter it - but so that an instance
// of it is visible throughout the scope of the function / script you are working with
$error = false;
if ($value == 1) 
{
    $error = "Fail";
}
// Now when you get here it will be defined irrespective of what $value's value is
if ($error) {
   // Do something
}

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 41848314
It is axiomatic in computer science and professional programming that you must  define your variables before using them.  An undefined variable is often a typographical error, and may result in unpredictable behaviors.  But there is nothing about PHP that upholds traditional rules of computer science and professional programming.  In fact, it was deliberately designed to be "easy," where "easy" meant you could ignore the axioms, and this led to a host of unfortunate language choices.

One such choice is the use of undefined variables.  PHP will let you use undefined variables, and it will automagically substitute one of the "falsy" values.  The exact value will depend on the context -- it will usually be zero or null.  When PHP makes such a substitution, it raises the "Notice" you've seen from your code.

But here is another unfortunate choice.  In the "default" PHP installation, the Notice messages are suppressed.  This led a generation of PHP programmers to the worst-practice of ignoring the rules about defining variables before using them.  Trouble is, when the Notice is ignored, some behavior of our programming is getting ignored, too.  If you want to see the Notice messages (and trust me, you really want to see all  the messages) you have to go out of your way and turn up the error_reporting() level.  When you do that, and you start seeing the Notice messages, it's sometimes a surprise.

You can define $error and $message before using them with a simple assignment statement like this
$error = $message = NULL;

Open in new window

You can also take advantage of empty() like this
if (!empty($error)) echo $error;

Open in new window

Either approach (or both if you'd like) will remedy the condition that is causing the unwanted Notice.
0
 

Author Comment

by:Ridgejp
ID: 41848325
Apologies ... I wrongly just grabbed lines 133 - 139 forgetting it would be re-jigged when placed into the code box. The full code is here ...

<!DOCTYPE html>
<?php
    include("inventoryadd.php");
    require_once("rev_config.php");

    $uid = access_control();

?>

<html lang="en">
<head>
			<meta charset="utf-8">
			<meta http-equiv="X-UA-Compatible" content="IE=edge">
			<meta name="viewport" content="width=device-width, initial-scale=1">
			<title>Adding New Products</title>

			<!-- Bootstrap -->
			<link href="css/bootstrap.min.css" rel="stylesheet">
			<link rel="stylesheet" href="../assets/bootstrap/css/bootstrap.min.css">
    		<link rel="stylesheet" href="../assets/bootstrap-table/src/bootstrap-table.css">
    		<link rel="stylesheet" href="../assets/examples.css">
    		
    		<script src="../assets/jquery.min.js"></script>
    		<script src="../assets/bootstrap/js/bootstrap.min.js"></script>
    		<script src="../assets/bootstrap-table/src/bootstrap-table.js"></script>
    		<script src="../assets/bootstrap-table/src/extensions/filter-control/bootstrap-table-filter-control.js"></script>
    		<script src="../ga.js"></script>
    		
    		<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
			<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
			<!-- Include all compiled plugins (below), or include individual files as needed -->
		
<style>

	.navbar-brand {
			font-size:1.6em;
			}

	#headerNav	{
				padding-left:10px;
				padding-bottom:10px:
				}

	h3, h5	{
			padding-left:10px;
			padding-right:10px;	
			}

	#table	{
			padding-left:10px;
			padding-right:10px;	
            font-size:0.8em;
			}

	#dropdownButton	{
			padding-left:10px;
			padding-bottom:10px:
			float: right;
			}
			
	#dropdownMenu1	{
			float: left;
			}
	
	#uList	{
			float: right;
			}
			
	#divFilter {
		float:right;
			}

</style>

</head>


	
<body>
<!-- Google Analytics Tab -->
<?php include_once("analyticstracking.php") ?>
    
<!-- Start of Container Class (1) -->
<div class="container">

<nav class="navbar navbar-default navbar-fixed-top">
  <div class="container">
      
  	<div class="navbar-header">
      <a class="navbar-brand">Home</a>
    </div>
    <a href="rev_logout.php" class="btn btn-danger navbar-btn pull-right" role="button">Log Out</a>
  
    </div>
</nav>

</br>	


<!-- Tab Headings -->
<ul class="nav nav-tabs" role="tablist">
    <li role="presentation"><a href="dashboard.php">Dashboard</a></li>
    <li id="headerNav" role="presentation" class="active"><a href="#">Inventory</a></li>
    <li role="presentation"><a href="stock.php">Current B.O.M</a></li>
  	<li role="presentation"><a href="assemblyid.php">B.O.M</a></li>
  	<li role="presentation"><a href="goodsin.php">Goods In</a></li>
    <li role="presentation" class="dropdown">
    <a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
      Actions <span class="caret"></span>
    </a>
    <ul class="dropdown-menu">
        <li><a href="">Add New Products</a></li>
    			<li><a href="">Update Existing Products</a></li>
    			<li role="separator" class="divider"></li>
    			<li><a href="inventory.php">Return to Inventory</a></li>
    </ul>
</ul>
	
</br>
</div>	


	<div class="container contentContainer" id="topContainer">

		<div class="row">

				<div class="col-md-6 col-md-offset-3" id="topRow">

				<h2 class="marginTop">Ok, let's add some products...</h2>
                
                    <?php
			
				    if ($error) {
			
					   echo '<div class="alert alert-danger">'.addslashes($error).'</div>';
			
					   }
			
				    if ($message) {
			
					   echo '<div class="alert alert-success">'.addslashes($message).'</div>';
			
					   }
			
				    ?>
			
			<form class="marginTop" method="post">
		                    
                    <div class="form-group">
						<label for="partID">Part ID</label>
						<input type="partID" name="partID" class="form-control" placeholder="Enter the product partID..."/>
					</div>
					
					<div class="form-group">
						<label for="partDescription">Description</label>
						<input type="partDescription" name="partDescription" class="form-control" placeholder="Enter the product sku..."/>
					</div>
					
					<div class="form-group">
						<label for="qtyInStock">Quantity</label>
						<input type="qtyInStock" name="qtyInStock" class="form-control" placeholder="Add initial stock quantity..."/>
					</div>
                    
					<div class="form-group">
						<label for="supplierCompany">Supplier</label>
						<input type="supplierCompany" name="supplierCompany" class="form-control" placeholder="Add supplier details..."/>
					</div>
					
					<div class="form-group">
						<label for="supplierCode">Supplier Code</label>
						<input type="supplierCode" name="supplierCode" class="form-control" placeholder="Add supplier part_no..."/>
					</div>
					
					<div class="form-group">
						<label for="supplierDesc">Supplier Description</label>
						<input type="supplierDesc" name="supplierDesc" class="form-control" placeholder="Add supplier description..."/>
					</div>
					
					<div class="form-group">
						<label for="itemCost">Unit Price (£)</label>
						<input type="itemCost" name="itemCost" class="form-control" placeholder="Add cost price..."/>
					</div>
					
					<div class="form-group">
						<label for="cartonSize">Carton Size</label>
						<input type="cartonSize" name="cartonSize" class="form-control" placeholder="Add carton size..."/>
					</div>					

					<input type="submit" name="submit" value="Add Now" class="btn btn-success btn-lg marginTop" />
	
			</form>
	
	</div>
	
	</div>

	</div>
	


		<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
		<!-- Include all compiled plugins (below), or include individual files as needed -->
		<script src="js/bootstrap.min.js"></script>
		
		<script>$(".contentContainer").css("min-height",$(window).height());</script>

</body>
</html>


	

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41848332
Do a search on that code for $error
What do you find?
The first time $error is encountered is on line 133 in an if statement - which is going to cause the error.

Where is the confusion here?

Where is $error being set?
0
 

Author Closing Comment

by:Ridgejp
ID: 41848377
Hi Ray,

Thanks as always for the back-ground information ... now I also "understand" why this is in-correct.

I've plenty more to do ... so no doubt will be back soon.

Thanks J.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction We as admins face situation where we need to redirect websites to another. This may be required as a part of an upgrade keeping the old URL but website should be served from new URL. This document would brief you on different ways ca…
It’s 2016. Password authentication should be dead — or at least close to dying. But, unfortunately, it has not traversed Quagga stage yet. Using password authentication is like laundering hotel guest linens with a washboard — it’s Passé.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now