wantTheBest
wantTheBest

Reputation: 1720

Php and forms problem

This is my super-simplified index.php:

<?php
    require_once 'DeleteOrAdd.php';  // handles adding/deleting a db record


    doAddDeleteRecord();
    // other functions are called here, left out though for brevity
 ?>

Here's DeleteOrAdd.php (much simplified)

<?php
    function doAddDeleteRecord()
    {
         echo <<<_END
             <form action="index.php" method="post">

                // the other form html not shown here

             <input type="submit" value="ADD RECORD" />
             </form>
_END;        

     // NOT SHOWN -- code to handle the form when it is POST'd

    }
 ?>

So it's late 10:30pm, I'm new to PHP, okay /excuses. Can't figure out how to do this.

I want to change my form action="index.php" above to form action="DeleteOrAdd.php" (ie. I want to re-post to the same file that this form is in, not to index.php, so the code is cleaner). but it won't work because I have all the form-handling logic for the POST -- inside the doAddDeleteRecord() function, so if I set my form action="DeleteOrAdd.php" it won't work.

Is it possible to do something like form action="DeleteOrAdd.php:doAddDeleteRecord()?

I don't want to put this in classes. I also want to keep my index.php just as it is above -- calling functions and no major inline code beyond that.

Any ideas?

Originally, all the code was inline inside index.php (got it from a PHP book's sample) and I then divided the code into logically-named PHP files in the Netbeans project to clean it up, and to put stuff in functions that get called from index.php.

Upvotes: 1

Views: 125

Answers (4)

Rufinus
Rufinus

Reputation: 30773

remove the action value completly from the form, default it will post always back to the url on which it is displayed.

<form action="" method="POST">

Upvotes: 2

OpenSorceress
OpenSorceress

Reputation: 2014

Foreword: Since you say this as a learning exercise, I'll skip past the sanctimonious manifesto on best practice and the many and sundry virtues of OOP. ;) Your book probably details every dire warning / stern lecture I'd normally prepend to a solution like this anyway.

Is it possible to do something like form action="DeleteOrAdd.php:doAddDeleteRecord() ?

In short, yes. The easiest way to accomplish your goal is to just reference your file in your form action, as you've done:

<!-- form.php -->
<form action="DeleteOrAdd.php" method="POST">

And then in DeleteOrAdd.php, trigger your function by testing the $_POST data your form submit will send in, like so:

<?php
// DeleteOrAdd.php

if(isset($_POST['some_form_variable']) && $_POST['some_form_variable'] != null) {
    $data = array();
    foreach($_POST as $post) {
        array_push($data, $post);
    }
    doAddDeleteRecord($data);
}

function doAddDeleteRecord($data) { 
     // ...your processing code, etc.

The upshot to a purely procedural approach like you've specified is quite frankly, you can do stuff like this. You wouldn't want to develop like this in real life (skipping this deep-dive too, I guarantee your book explains why not in exhaustive detail.)

Important note!! Since I didn't see a return value in the code snippet you posted, and you say you're just getting started, I'm going to take a minute and point out a hidden pitfall here just in case:

--> Your code might work perfectly with those six lines I added above your function, and you'd never know it if you're not

  1. returning a value (which proves the code ran, if nothing else) and

  2. capturing said value so you can act on it / display it / otherwise show yourself that

    a. something happened -- and ideally,
    b. what that something was.

Otherwise, all you've got is ambiguity: no indication it's either working or breaking (not throwing errors, warnings, etc). Frustrating to debug, to say the least.

So, that stated -- presuming you've got your function returning something (true on success, string with a message, whatever) it probably goes something like this:

function doAddDeleteRecord($data) {
    // ... your function code, etc.
    $sql = "INSERT INTO mytable VALUES(".implode(',',$data).")";
    if (mysql_query($sql) == true) { 
        $message = "Record saved";
    } else {
        $message = false;
    }
    return $message;
}

Any value your function returns needs a variable to capture it or it won't be set. Capture it with a variable assignment when you call your doAddDeleteRecord() function:

 ... // same 6 little lines of conditional code ...
    }
    $result = doAddDeleteRecord($data);
 }
 // maybe just echo it out or something...
 echo $result;

-- or --

  ... // still the same 6 lines ...
     }
     $result = doAddDeleteRecord($data);
  }
  // maybe have a new test based on the outcome of the last one...
  if ($result == false) { 
      // do something about the fail...
  } elseif (is_string($result)) {
      // do something about the success...
  }

Good luck, HTH. :)

Upvotes: 0

Brian Patterson
Brian Patterson

Reputation: 1625

I think the problem you have here is being able to make your PHP page discern between whether or not its a fresh load or whether or not its submission of the form, and that is why your incorporating the index page in your action parameter. However, this is not necessary.

Set the id and name (for valid markup) attribute of your submit element to a unique name. Such as "form_submit" so here is an example.

<form action="" method="post">

<input type="submit" id="form_submit" name="form_submit" value="ADD RECORD" />

</form>

So what you put in your PHP script (doAddorDelete.php) is this ...

 if (array_key_exists('form_submit', $_POST)) {

    //this is the code to execute on form submit
    //use print_r($_POST) to view variables you can use here
    //make sure you validate all data passed here especially if using a database
    //ie if MySQL
    //$validated_userinput = mysql_real_escape_string(strip_tags(htmlentities(trim($_POST['userinput']))), $link_resource); for text
    //(int) $_POST['userinput'];  for numbers


    } else {
         echo <<<_END
                 <form action="" method="post">

                    // the other form html not shown here

                 <input type="submit" id="form_submit" name="form_submit" value="ADD RECORD" />
                 </form>
    _END;
    }

Hope this helps! :)

Upvotes: 1

Shakti Singh
Shakti Singh

Reputation: 86476

Your application is not well structured. I would recommend to follow MVC pattern.

But for your current problem you can do something like this

just set the action to your <form action="DeleteOrAdd.php" or you can leave the action completely blank which post your data on the same file in which the form is created.

When the form is posted your could do below in your DeleteOrAdd.php file.

if (isset($_POST['submit']))
{
  doAddDeleteRecord();// this will call your 
}

but in this case you may have to change the code of your index.php

Upvotes: 1

Related Questions