5 Replies - 4240 Views - Last Post: 07 August 2012 - 04:39 PM Rate Topic: -----

#1 synlight  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 84
  • View blog
  • Posts: 557
  • Joined: 14-September 11

Dynamic radio buttons, passing selection to query

Posted 07 August 2012 - 10:38 AM

I'm working with a database that has a table called Products. Each product belongs to a department. I'm sending a query to the database to dynamically generate radio buttons for the use to select a department, which is working fine. I then use the selection they make to generate a list of products that are in that department (books, movies, etc)

The radio buttons are rendering fine, but when I try to query the database using the selection I'm getting an undefined variable name error. I know this has to do with the way I'm passing the variable..

Here is where the radio buttons are created:

  
$query = "SELECT DISTINCT department FROM products";
$result = mysql_query($query);
 //Start a while loop to process all the rows
    while ($row = mysql_fetch_assoc($result))
      {
        $dept = $row['department'];
?>
        <input type="radio"  value="<?php echo $dept; ?>"name"='department'><?php echo $dept; ?>
<?php
      } //END WHILE
?>

          <p /><input type = "submit" value = "SUBMIT"><input type = "reset" value = "CLEAR">
          <input type="hidden" name="username" value="<?php echo $username;?>">
          <input type="hidden" name="choice" value="<?php echo $dept;?>">
          </form></font></body></html>



And here is where I am trying to use the variable choice to make another query:

<?php
    $query = "SELECT * FROM products WHERE department = '$choice'";
    $dept = $choice;
    $result = mysql_query($query);

    //Start a while loop to process all the rows
    while ($row = mysql_fetch_assoc($result))
      {
        $ID                = $row['ID'];
        $entertainerauthor = $row['entertainerauthor'];
        $title             = $row['title'];
        $media             = $row['media'];
        $feature           = $row['feature'];
        
?>


Any direction would be appreciated!

Is This A Good Question/Topic? 0
  • +

Replies To: Dynamic radio buttons, passing selection to query

#2 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 434
  • View blog
  • Posts: 1,042
  • Joined: 08-March 09

Re: Dynamic radio buttons, passing selection to query

Posted 07 August 2012 - 11:01 AM

Hi,

Assuming your form's method is POST you will find the selected radio button in the $_POST superglobal associative array. They key will be the name of the form element. So in your case you can find the selected radio like so:
echo $_POST['department'];




You would most likely want your query to be something like:
"SELECT * FROM products WHERE department = $_POST[department]";



This stuff is of course open to SQL injection. Also the mysql* functions are deprecated and shouldn't be used. PDO is much more robust and secure.

Hope this helps :)
Was This Post Helpful? 1
  • +
  • -

#3 synlight  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 84
  • View blog
  • Posts: 557
  • Joined: 14-September 11

Re: Dynamic radio buttons, passing selection to query

Posted 07 August 2012 - 11:25 AM

View PostJstall, on 07 August 2012 - 01:01 PM, said:

Hi,

Also the mysql* functions are deprecated and shouldn't be used. PDO is much more robust and secure.

Hope this helps :)


Ugh I just took an 8 week course using those commands. WHY does my school do that?! Did the same thing in my Java class.

Okay, so I tried what you suggested.:

 extract($_POST); //EXTRACT form
 $dept = $_POST['department'];

 $query = "SELECT * FROM products WHERE department = '$dept' ";






And I am now getting a different error:

Undefined index: department


Does this mean that my previous form is not passing the selection from the radio button? The only thing I can think is that the selected value is being destroyed when the while loop is exited?

I'm really confused.
Was This Post Helpful? 0
  • +
  • -

#4 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3635
  • View blog
  • Posts: 5,756
  • Joined: 08-June 10

Re: Dynamic radio buttons, passing selection to query

Posted 07 August 2012 - 02:32 PM

Getting an "Undefined index" array means you are trying to access array elements that don't exist. In the case of POST and GET data, it means those user inputs were never sent.

Having your script depend on the questionable assumption that user input will exist is very dangerous. Thankfully PHP provides us with the isset and empty functions, which you can (and should!) use to verify user input before using it. - The difference between those two is that, using the empty() function will not only ensure that the fields were sent, but it will also make sure they have a value. If you only need to make sure the fields were sent, use isset().

For example:
if (!empty($_POST["field1"]) && !empty($_POST["field"])) {
    // Fields were sent, and they have a value!
    // Use them as you see fit...

    // As an example, to securely use user input with
    // the old MySQL functions... 
    $sql = "SELECT stuff FROM stuffTable
            WHERE first = '%s' AND second = '%s'";

    $sql = sprintf($sql, mysql_real_escape_string($_POST["field1"]),
                         mysql_real_escape_string($_POST["field2"]));

    mysql_connect("localhost", "User", "PWd") or die("Connection failed.")
    mysql_select_db("dbname") or die("DB Selection Failed");
    $result = mysql_query($sql) or die("Query failed");

    while ($row = mysql_fetch_assoc($result)) { ... }

    // And now, the same thing in PDO...
    $dbLink = new PDO("mysql:host=localhost;dbname=test", "User", "Pwd");

    $sql = "SELECT stuff FROM stuffTable
            WHERE first = ? AND second = ?";
    $stmt = $dbLink->prepare($sql);
    $stmt->execute(array($_POST["field1"], $_POST["field2"]));

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ... }
}
else {
    echo "Can't proceed without data!";
}



There was one thing in your original code that could be causing trouble. This line in your first snippet:
<input type="radio"  value="<?php echo $dept; ?>"name"='department'><?php echo $dept; ?>


The quotes marks don't add up. You've got an extra " between the "name" attribute and it's value. The end result of that code would look something like:
<input type="radio"  value="dept_value"name"='department'>....


The browser may be reading that as invalid syntax and throwing the name value out.


By the way, there is one other thing I'd like to point out. Doing extract($_POST); is not a good idea. It's a "workaround" to bypass the removal of the register_globals feature, which allowed you to access request variables (POST and GET) as variables, rather than array elements. Essentially, it allowed you to do: $field1 instead of $_POST["field1"]. - This was disabled and removed from PHP for security reasons (read about that in the link I posted.) Naturally, replicating a feature like that is a bad idea. At least unless you fully understand what it does and why it's a risk.


View Postsynlight, on 07 August 2012 - 06:25 PM, said:

Ugh I just took an 8 week course using those commands. WHY does my school do that?! Did the same thing in my Java class.

The fact is that, even though PDO and MySQLi are taking over from the old MySQL functions, they aren't going anywhere anytime soon. A lot of existing code still requires you to use them, and many developers are reluctant to let go of them. - Odds are that, as a PHP developer, you will need to know how to use them. Not teaching them would be a major hole in any PHP developer's education.

Of course, any decent school should also be teaching you not to use them, and preaching PDO and/or MySQLi instead.
Was This Post Helpful? 2
  • +
  • -

#5 synlight  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 84
  • View blog
  • Posts: 557
  • Joined: 14-September 11

Re: Dynamic radio buttons, passing selection to query

Posted 07 August 2012 - 03:55 PM

View PostAtli, on 07 August 2012 - 04:32 PM, said:

extract($_POST); is not a good idea. It's a "workaround" to bypass the removal of the register_globals feature

I didn't know that. There are several methods in our textbook, but my instructor told us we were to use the EXTRACT $POST method ONLY.



Of course, any decent school should also be teaching you not to use them, and preaching PDO and/or MySQLi instead.


I'm starting to wonder if I'm going to a decent school, honestly.

Thank you for such a thorough reply. I am only my final project for this class, and I enjoy PHP, so I do plan to continue studying on my own.

I have been working on this all day. I've waded through several other issues, but no matter what radio button the user chooses, it only displays the 3rd and final department, which is Music. By my logic, this has to do with the way I am handling the while loop that renders my radio buttons. It is returning the name of the last department, not the department that is selected. I have 5 separate php files in this website, and they ALL depend on choosing the right department. I will post the code below, and ANY help ANYONE can give would be appreciated. I am going cross eyed looking at it, and I just can't find the problem. My code is going to look simplistic to everyone, and probably like I am doing stupid crap.

<pre>
<?php
//FILENAME : BB1.php
//PROGRAMMER : Synlight
//PURPOSE : Show departments

          extract($_POST); //EXTRACT form
          
          if ($enter == 2)
          {
             printf("<h2>We hope to see you again soon at BB's Online Superstore!!</h2>");
             echo ('<img src="sadface.jpg">');
          }
          else
          {
              if (empty($username)) //check for username
                 printf("<h2>You did not enter a user name. Please press the BACK button.\n</h2>");
          }

                 $link = mysql_connect("localhost", "root", "pw"); //Connect to the database
                 if (!$link)
                    die("Could not connect: " . mysql_error());

                 if (!mysql_select_db("cpt283db"))
                    die("Problem with the database: " . mysql_error());
             
                 $query = "SELECT DISTINCT department FROM products";
                 $result = mysql_query($query);
?>

<!doctype html public "-//W3C//DTD HTML 4.0 //EN"><html><head></head>
<body bgcolor = "#B4CDCD">
<font face = "verdana">
<form action = "BB2.php" method = "POST">
<h1>BB's Online Superstore</h1>
<fieldset><legend>Please select any department you would like to know more about:</legend>

<?php
    //Start a while loop to process all the rows
    while ($row = mysql_fetch_assoc($result))
      {
        $dept = $row['department'];


		?>
        <input type="radio" value= "$dept" name= "dept"><?php echo $dept;
      } //END WHILE
?>
         </fieldset><br>
          <input type = "submit" value = "SUBMIT">
          <input type = "reset" value = "CLEAR">
          <input type="hidden" name="username" value="<?php echo $username;?>">
          <input type="hidden" name="dep" value="<?php echo $dept;?>">
          </form></font></body></html>

<?PHP
    mysql_close($link); //Close the db connection
//END ELSE connection

?>
</pre>




Was This Post Helpful? 0
  • +
  • -

#6 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3635
  • View blog
  • Posts: 5,756
  • Joined: 08-June 10

Re: Dynamic radio buttons, passing selection to query

Posted 07 August 2012 - 04:39 PM

On line #46 of that code, you do value= "$dept" inside the radio input tag. However, notice how $dept is not inside PHP tags. As a result, it won't be executed as PHP code and instead of printing the $dept value, it'll just send "$dept" as a string to the browser. - This will cause incorrect values to be used when the radio buttons are sent to the BB2.php code.

This is one risk of mixing your PHP and HTML code together like that. It blurs the lines between PHP and HTML, making it easier for mistakes like these to get past you. - This is how everybody starts writing PHP sites, but once you start doing things above a certain level of complexity, it's just not a viable method of coding.

It probably won't do you any good for your current project, as I am assuming you won't have time to rewrite the whole thing, but when you get the time, I suggest you study Code Separation. It'll make your code easier to work with.

synlight said:

My code is going to look simplistic to everyone, and probably like I am doing stupid crap.

Don't worry. Everybody starts at the beginning. You'll no doubt be arguing with us about your favorite design patterns and frameworks in no time ;)

synlight said:

I'm starting to wonder if I'm going to a decent school, honestly.

I wouldn't worry about it. A lot of schools tend to teach outdated methods. It's sort of understandable, seeing how fast programming languages evolve. It's no doubt tricky to find a way to teach you what you need to know to maintain existing code using old methods, as well as develop new code according to new methods. Most teachers will probably just teach you the old stuff and trust you to find out the new stuff on your own. - You'll be doing that your entire programming career anyways. Programming requires non-stop self education, just to keep up.

However, the extract($_POST); method was never a good idea. I don't know why anybody would teach that...

This post has been edited by Atli: 07 August 2012 - 04:40 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1