if statement for Form field and database insert

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
churd
Forum Newbie
Posts: 8
Joined: Tue Feb 09, 2010 7:44 pm

if statement for Form field and database insert

Post 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.
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: if statement for Form field and database insert

Post 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.
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply