Php – Button Element with Type Submit & PHP Challenges

buttondatabaseelementphpsubmit

Recently I change from <input type="button"> to <button> in my forms however the form being processed by PHP wouldn't then submit to the database. Am I missing something in my code?

Basically all I have done is changed this:

<input type="submit" name="submitAdd" value="Ask Question! " />

To this:

<button type="submit" class="btn" name="submitAdd"><span><span>Ask Question!</span></span></button>

Here is the basic PHP processing Code:


//Extract question from submission
$question = (isset($_POST["question"]))?$_POST["question"]:"";
$question_date = (isset($_POST["question_date"]))?$_POST["question_date"]:"";
$submitAdd = (isset($_POST["submitAdd"]))?$_POST["submitAdd"]:"";

//Open connect to database 
include("include/session.php");

//Prepare data for submission
$db_question = addslashes($question);
$db_question_date = addslashes($question_date);

//If form has been submitted, insert question into database
if ($submitAdd) {
    $sql ="INSERT INTO questions
    (question,question_date)
    VALUES ('$db_question', '$db_question_date')";
    $result = mysql_query($sql);
    if (!$result) {
        $message = "Failed to add question. MySQL said " . mysql_error();
    } else {
        header("Location:http://localhost/grill/register.php"); 
    }
}

Best Solution

It doesn't work because the button version has no value. Your code says:

$submitAdd = (isset($_POST["submitAdd"]))?$_POST["submitAdd"]:"";

but you have:

<button type="submit" class="btn" name="submitAdd"><span><span>Ask Question!</span></span></button>

Compare this to:

<input type="submit" name="submitAdd" value="Ask Question! " />

which has a value attribute. This value is passed to the PHP script and is what you're testing. Your <button> doesn't have one.

With no value $submitAdd, even when clicked, will have a value of ''. An empty string evaluates to false when you do this:

if ($submitAdd) {

So, a couple of changes I would recommend. Firstly, change this:

$submitAdd = (isset($_POST["submitAdd"]))?$_POST["submitAdd"]:"";

to

$submitAdd = isset($_POST['submitAdd']);

since you don't really care about the value.

Secondly, unrelated to this but still worth mentioning, I would do this:

$db_question = mysql_real_escape_string($question);
$db_question_date = mysql_real_escape_string($question_date);
$sql = <<<END
INSERT INTO QUESTIONS (question, question_date)
VALUES ('$db_question', '$db_question_date')
END;
Related Question