[SOLVED] Question about setting a variable dependant on form data


#1

Hello all,

I am trying to set a variable that can come from one of two places. Either a form or from a mysql select.

I’ve tried the below but i a blank variable if the form data is blank but it has the correct data if the form data is set. I think it’s because I am defining the variable twice even though it’s within an if statement

I have trimmed out the extra code. It correctly pulls the data out of the DB if I don’t have the if statement but with it

while($row = $result->fetch_assoc()) {
    if(isset($_POST['carreg'])){
        $carreg = $_POST['carreg'];
    }else{
        $carreg = $row['carreg'];
    }
}

Any help would really be appreciated, I am sure it’s something simple

Summary

This text will be hidden


#2
  1. Before the start of the form processing code, define an empty array variable (even if the form and sql query only has a single field) to hold a ‘working’ copy of the data in question.

  2. Inside the form processing code, after you have detected that a post method form was submitted, copy/assign the $_POST array to the variable created in step #1, optionally trimming all the values at once to help when detecting if all white-space characters were entered.

  3. After the end of the form processing code, if the variable created in step #1 is an empty array (the form processing code has never been executed), run the sql query code and fetch the row of data into the variable.

  4. Use elements in the array variable in the remainder of the code. It will initially contain the result from the query. After the form has been submitted, it contains the submitted form data.


#3

Thank you phdr, I’ve not really worked with array’s (unless unknowingly) so I don’t know if I did what you meant, But it’s working now I followed your workflow for the code.

$carreg = “”;
Outside the form processing

$carreg = $_POST[‘carreg’];
Inside the the detection of form submission

$carregdb = $row[‘carreg’];
Inside the mysql query

if(empty($carreg)){
$carreg = ‘’.$carregdb;
}
after the mysql query