troubleshooting Question

Form validation using functions

Avatar of Crazy Horse
Crazy HorseFlag for South Africa asked on
PHP
27 Comments2 Solutions166 ViewsLast Modified:
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";
				

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>

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";

Perhaps I should rather exclude the validation from the function, perform it on the page and if it passes, then only call the function?
ASKER CERTIFIED SOLUTION
Marco Gasi
Freelancer

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Top Expert 2010

The Distinguished Expert awards are presented to the top veteran and rookie experts to earn the most points in the top 50 topics.

Join our community to see this answer!
Unlock 2 Answers and 27 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 27 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros