Monday, July 9, 2018

php - Why am I getting these undefined index errors?




Why am I having undefined index errors here on my code when I add the sort feature? These are the errors I'm getting





Notice: Undefined index: sort in C:\xampp\htdocs\how are things\admin panel\view.php on line 58



Notice: Undefined index: sort in C:\xampp\htdocs\how are things\admin panel\view.php on line 61



Notice: Undefined index: sort in C:\xampp\htdocs\how are things\admin panel\view.php on line 64



Notice: Undefined index: sort in C:\xampp\htdocs\how are things\admin panel\view.php on line 67




Notice: Undefined index: sort in C:\xampp\htdocs\how are things\admin panel\view.php on line 70



Notice: Undefined index: sort in C:\xampp\htdocs\how are things\admin panel\view.php on line 73



Notice: Undefined index: sort in C:\xampp\htdocs\how are things\admin panel\view.php on line 76




This is the code on the lines 58 61 64 67 70 73 76



$result = "SELECT * FROM customers";

if($_GET['sort'] == 'first_name'){
$result .= " ORDER BY first_name";
}
else if($_GET['sort'] == 'last_name'){
$result .= " ORDER BY last_name";
}
else if($_GET['sort'] == 'address'){
$result .= " ORDER BY address";
}
else if($_GET['sort'] == 'phone_number'){

$result .= " ORDER BY phone_number";
}
else if($_GET['sort'] == 'email'){
$result .= " ORDER BY email";
}
else if($_GET['sort'] == 'city'){
$result .= " ORDER BY city";
}
else if($_GET['sort'] == 'country'){
$result .= " ORDER BY country";

}
$result = mysql_query($result) or die(mysql_error());

Answer



you should check if sort is set and then use it. maybe something like this would work for you:



    $allowedSorts = array('first_name', 'last_name', 'address','phone_number', 'email', 'city', 'country');

$sort = isset($_GET['sort']) ? $_GET['sort'] : '';
$result = "SELECT * FROM customers";

if(in_array($sort, $allowedSorts)){
$result .= " ORDER BY {$sort}";
}

$result = mysql_query($result) or die(mysql_error());

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...