1

I'm having trouble with a PHP switch function.

Based on the users selection I would like to populate the input "destination" with the selections corresponding value from the switch function. Unfortunately when I try to run the code on my dev. server I keep getting 'variable undefined'.

Edit

I just want to add that it's important my select and option values remain the same as I have a script that relies on them.

Second Edit

The goal is for my "dropdown" element to populate my object and for the "destination" input to be a unique description of that object (populated by the values given in my switch example).

<?php

if(isset($_POST['dropdown']))
switch ($_POST['dropdown'])  { 
case "Data1": $input = "Data1Value"; break;
case "Data2": $input = "Data2Value"; break;
case "Data3": $input = "Data3Value"; break;
}
?>

<form method="POST">
<select name="dropdown" id="dropdown">
<option value="Data1">Data1</option>
<option value="Data2">Data2</option>
<option value="Data3">Data3</option> 
</select>

<input id="destination" name="destination" value="<?php echo $input ?>">

</form>

I'm open to other suggestions on obtaining my desired result if this is the not the best way to go. I appreciate any assistance you might be able to provide.

1
  • @Tuga you don't get a warning for the undefined $input? Commented Jan 10, 2014 at 0:46

4 Answers 4

2

As already stated, the undefined variable is due to your page getting an empty $_POST result as long as the first form has not been submitted. For your switch to work, you have to hit a submit button (which currently does not exist, unfortunately :)), so that the page reloads with the proper POST data.

I assume you might want something like this:

<?php
if(isset($_POST['destination']))
{
    $destinations = array (
        "Data1" => "Data1Value",
        "Data2" => "Data2Value",
        "Data3" => "Data3Value");
    $dest = $destinations[$_POST['destination']];

    echo "<p>destination set from POST vars: <b>$dest</b></p><br />";
    // do whatever you want with your destination
    // (presumably redirect to another page)
    // travel_to ($dest);
    die(); // redirecting should make you leave the page
}
?>

<form method="POST">
    <select name="destination">
        <option value="Data1">Data1</option>
        <option value="Data2">Data2</option>
        <option value="Data3">Data3</option> 
    </select>
    <input type='submit' value='Travel!'>
</form>

A few comments:

  • renamed "dropdown" to something more meaningful. Bad names make bad code.
  • added the submit button without which you could never send the form (except with the help of some JavaScript, but that's another story)
  • removed the hidden input, which I think was showing a bit of confusion between the initial page (where the select defines your destination) and the final page (where the POST data retrieves the destination via the select value)
  • replaced the switch with an array. Associative array are the bread and butter of PHP (well, among other things :)). Better get used to them as quick as possible, you very probably won't regret it.

Note that the page doing the input and the one processing the POST data are often two separate HTML/PHP files. Doing both from the same file is easier to test, but might be a bit confusing.

EDIT:

Fiddling with databases is an entirely different question, and I could get scolded for straying way off topic but, for the sake of completeness, here is a rough sketch of what you could do.

Note that you will have to create the database and the table that will hold the record.

Note also that this code will not run out of the box.
You will have to fill-in the blanks by yourself, using the PHP manual.
Especially, I left error handling out for concision.

<?php
if(isset($_POST['value_selector']))
{
    $data_values = array (
        "Data1" => "Data1Value",
        "Data2" => "Data2Value",
        "Data3" => "Data3Value");
    $value = $data_values[$_POST['value_selector']];

    // now that you've got your value, let's cram it into a DB!

    // see PHP manual for details
    // --------------------------
    // you'll need to create a base named "database"
    // with a table named "data_table"
    // containing a field named "data"
    // and provide a host, user name & password for the MySQL connection
    // 
    $DBH = new PDO("mysql:host=$host;dbname=database", $user, $pass); 
    $DBH->exec("INSERT INTO data_table ( data ) values ( '$value' )");

    // done!
    echo "<p>value of <b>data</b> set from POST vars to <b>$value</b></p><br />";
    die();
}
?>

<form method="POST">
    <select name="value_selector">
        <option value="Data1">Data1</option>
        <option value="Data2">Data2</option>
        <option value="Data3">Data3</option> 
    </select>
    <input type='submit' value='Store that data!'>
</form>
Sign up to request clarification or add additional context in comments.

11 Comments

Essentially, I am trying to populate two different database items with one select box. The original "dropdown" in my example would be the object and the "destination" text box I am trying populate would be a description. Unfortunately, this solution will not work for me. I really like this suggestion though and I hope you can expand on it to meet my needs. I really appreciate your help!
Fortunately, it will :) Just update your question and I'll update my answer
It is done, I hope I am being clear. I'm new to programming and this is essentially my last hang up in this project I'm working on.
Just to make sure I understand: you want the PHP code to add a record to a database (the kind of database you could handle with MySQL), containing two fields, for instance data="Data2" and description="Data2Value" if the user selected the 2nd dropbox option?
Yes, that's exactly right! If possible, I would like to retain the name of my original 'select' element but I understand if that is not possible. Many thanks for your help.
|
1

Your script is running fine. You look like you troubled with the message. Just disable the php error notice.

error_reporting( E_ALL ^E_NOTICE ); 

At the beginning of the script there is a variable $_POST ['dropdown']. If you need a default value at the beginning of your code, put that condition in your script.

if(isset($_POST['dropdown'])){
    switch ($_POST['dropdown'])  { 
        case "Data1": $input = "Data1Value"; break;
        case "Data2": $input = "Data2Value"; break;
        case "Data3": $input = "Data3Value"; break;
    }
}else{
    $input = "Some default value";  
}

Also consider that your ternary if this case can confuse you. So I put the keys in the sample.

7 Comments

error_reporting change is one way, but I just want to make sure that people know this is considered bad practise compared to just fixing the issue.
I showed just a way for him. He seems really uncomfortable with is the message. For as I said at the beginning of the variable POST code does not exist in him code.
I am all against advising a beginner to turn off warnings. Answers are supposed to help people improving their coding skills, and hiding the dust under the carpet rarely achieves that.
I think this suggestion is getting close, however, When I posted the form to my database it retained it's "Default" value rather than my desired input. Any suggestions?
Again, if you read his question will find that with notice when activated will show that there is no variable. Unless he put a @ at the beginning. It was just an attempt to help him.
|
0

When you first run your script and there is no $_POST['dropdown'], the $input variable is never set, and then when you go to echo it out, it will throw your undefined variable error.

Try checking if $input is set first with isset($input).

2 Comments

<?php echo isset($input) ? $input : ''; ?>
This loaded my page without errors but when I posted a test to my database the input was blank.
0

This works for me without any error or warning:

<?php
error_reporting(E_ALL); 
ini_set('display_errors', 1);

if(isset($_POST['dropdown']))
switch ($_POST['dropdown'])  { 
case "Data1": $input = "Data1Value"; break;
case "Data2": $input = "Data2Value"; break;
case "Data3": $input = "Data3Value"; break;
}else{
    $input = "Type something...";
}
?>

<form method="POST">
<select name="dropdown" id="dropdown">
<option value="Data1">Data1</option>
<option value="Data2">Data2</option>
<option value="Data3">Data3</option> 
</select>
<input id="destination" name="destination" value="<?php echo $input ?>">
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.