Reputation: 13
I have declared static array $error whose elements are defining in function validate
static $error = array();
if(!empty($_POST) && validate())
{
$sql = mysql_query("INSERT INTO `table-name` SET category = " . $_POST['category'] . ", brand = " . $_POST['brand'] . ", product = '" . $_POST['p_name'] . "', location = " . $_POST['location'] . ", image = '" . $_POST['image'] . "', sku = '" . $_POST['sku'] . "'");
}
function validate()
{
if ((strlen($_POST['p_name']) < 3) || (strlen($_POST['p_name']) > 32))
{
$error["p_name"] = "Please enter Vendor name of 3 to 32 characters." ;
}
.
.
.
}
but the problem is when i am using the updated $error element like $error['p_name'] in below html, it is showing undefined index p_name.
<td>
<?php if(isset($error["p_name"])){ ?><span class="error"><?php echo $error["p_name"]; ?></span><?php } ?>
</td>
and when I print $error['p_name']
element within validate function it get printed with updated value.
Actually element - $error['p_name']
in validate function is defining a new element rather than creating a new array element of predefined $error
array.
Upvotes: 1
Views: 44
Reputation: 68526
Well you didn't answer my comment. so it was the scope issue , Do not use global keyword. Use the Dependency Injection concept..
Pass your $error
array variable as a reference to your function..
function validate(&$error) //<---- Like that. (See the & ?)
{
and when you do a call to your validate
function make sure you pass the array too.
Upvotes: 1
Reputation: 23749
use global keyword to tell php, that you are using global $error:
function validate()
{
global $error;
if ((strlen($_POST['p_name']) < 3) || (strlen($_POST['p_name']) > 32))
{
$error["p_name"] = "Please enter Vendor name of 3 to 32 characters." ;
}
Upvotes: 1