We help IT Professionals succeed at work.
Get Started

Form validation using functions

Black Sulfur
Black Sulfur asked
on
163 Views
Last Modified: 2016-09-10
I am trying to learn how to use functions to make my code neater by not having loads of php in amongst the html. It seems to be working okay so far for making queries and inserting/editing/delete data in the database. But I am having an issue with validation.

Before the function I had:

 
       $error = "";
	$success ="";

		if(isset($_POST['submit'])) {
		if (empty($_POST['cat_title'])){
			
			$error .= "Category cannot be empty";
			
		} else {

		$cat_title = $link->real_escape_string($_POST['cat_title']);
		
			
			$sql = "INSERT INTO `categories`(cat_title) VALUES('$cat_title')";
			if ($result = $link->query($sql) == TRUE) {

			$success .="record added";
				

Open in new window


As soon as I put that into a function and call it on the page I want it on, I get a notice:

Undefined variable: error in /Applications/MAMP/htdocs/cms/admin/categories.php on line 54

Line 54 is:

<div><?php echo $error.$success;?></div>

Open in new window


This used to work just fine before using the function to call this code.

I defined the variable in the function and am calling the function before the $error.$success code so why is it saying the variable is undefined?

Here is the function:

function insert_categories(){
	
	global $link;

	$error = "";
	$success ="";


		if(isset($_POST['submit'])) {
		if (empty($_POST['cat_title'])){
			
			$error .= "Category cannot be empty";
			
		} else {

		$cat_title = $link->real_escape_string($_POST['cat_title']);
		
			
			$sql = "INSERT INTO `categories`(cat_title) VALUES('$cat_title')";
			if ($result = $link->query($sql) == TRUE) {

			$success .="record added";

Open in new window


Perhaps I should rather exclude the validation from the function, perform it on the page and if it passes, then only call the function?
Comment
Watch Question
Freelancer
CERTIFIED EXPERT
Top Expert 2010
Commented:
This problem has been solved!
Unlock 2 Answers and 27 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE