Page 1 of 1

if statement for Form field and database insert

Posted: Fri Mar 05, 2010 11:55 am
by churd
Here is a cut down version of what I'm doing... in the guts of my coding, I present a form field that is only active if a checkbox is checked (ie; Alternate Contact information)

Code: Select all

<input type="checkbox"  name="alternate_contact" id="alternate_contact" onClick="document.getElementById('wo_fname').disabled=(this.checked)?0:1;>
It then enables a field called "wo_fname", that is otherwise disabled:

Code: Select all

<input id="element_10_1" name= "wo_fname" class="element text" maxlength="255" size="14" value="" disabled/>
Then, upon submission, I am uploading that information to MySQL database:

Code: Select all

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO work_orders (wo_fname) VALUES (%s)",
                       GetSQLValueString($_POST['wo_fname'], "int");
(note that MM_insert is a hidden value submitted with the form submission)

Here's where I need help... if the box is NOT checked, and the form is submitted, I want to replace wo_fname with a variable that I have already successfully pulled into my code, and that I have already assigned to be wo_fname... it is being over-written, however, by the NULL value and the form is not submitting. What I need to do, is to write an If statement so that if the form field is NULL, then $wo_fname does not change to a NULL value.

Re: if statement for Form field and database insert

Posted: Sat Mar 06, 2010 11:27 am
by social_experiment

Code: Select all

<?php if (isset($_POST['MM_insert'])) && ($_POST['MM_insert'] == 'form1')) {
 if (trim($_POST['wo_fname']) == '') {
    $query = mysql_query("SELECT predefined_value FROM table");
    while ($pointer = mysql_fetch_array($query)) {
        $wo_fname = $pointer['predefined_value'];
    }
    $insert_query = mysql_query("INSERT INTO work_orders(wo_fname) VALUES ($wo_fname)");
    //adapt to fit in with your query.
 }
} ?>
Check if the form has been set / sent, then check if the value of $_POST['wo_fname'] is empty. If it is, call the value you predefined from the database (or assign it in the script) and then place it inside the query that writes to the database.

Hope this helps.