3

I'm building a single page application for finding a film based on genre. At the moment it uses the POST method on both the main form and the comments form.

The commments form currently gets the film ID using a GET method (this was chosen to avoid refreshing the page which resets the film suggestion process).

At the moment if I hit submit on the main form, the url changes to index.php? and the film successfully loads based on the criteria.

My question is: Why isn't my filmID echoing out in the main form? How can I stick the film ID into the current URL without using the GET method? So for instance if I typed in index.php?filmID=6 it would load up info about "The Dark Knight".

index.php (Trimmed by request)

        //If submit comment pressed, get data and input 
        if(trim($_POST['submit']) == "Submit comment"){ 

            $userID = $_SESSION['userID']; 
            $likeit = $_POST['yesornoList'];
            $filmID = $_GET['filmID']; 

            $comment = clean_string($db_server, $_POST['commentBox']); 
            if ($comment != '') { 
                $query = "INSERT INTO comments (userID, filmID, comment, likeit) 
                          VALUES ('$userID', '$filmID', '$comment', '$likeit')"; 
                mysqli_select_db($db_server, $db_database); 
                mysqli_query($db_server, $query) or 
                        die("Insert failed: " . mysqli_error($db_server)) . $query; 
                echo $commentMessage = "<section>Thanks for your comment!</section>"; 
            }

        }else{ 

            if (isset($_POST['genreList']) && ($_POST['genreList'] != "")){
                $genre = clean_string($db_server, $_POST['genreList']);
                //create the SQL query
                $query = "SELECT * FROM films WHERE genreID=$genre ";

                //$endquery = " AND (";
                $endquery = "";
                $orFlag = false;

                if (isset($_POST['streamingCheckbox1']) && ($_POST['streamingCheckbox1'] != '')){                   
                    $endquery .= " netflix IS NOT NULL";
                    $orFlag = true;
                }
                if (isset($_POST['streamingCheckbox2']) && ($_POST['streamingCheckbox2'] != '')){
                    if($orFlag){
                        $endquery .= " OR ";
                    }
                    $endquery .= " lovefilmInstant IS NOT NULL";
                    $orFlag = true;
                }
                if (isset($_POST['streamingCheckbox3']) && ($_POST['streamingCheckbox3'] != '')){
                    if($orFlag){
                        $endquery .= " OR ";
                    }
                    $endquery .= " blinkbox IS NOT NULL";
                }               
                if($endquery != "") $query .= " AND (" . $endquery . ")";
                $query .= " ORDER BY (SELECT FLOOR(MAX(filmID) * RAND()) FROM films) LIMIT 0,1;"; 

                //query the database
                mysqli_select_db($db_server, $db_database);
                $result = mysqli_query($db_server, $query);
                if (!$result) die("Database access failed: " . mysqli_error($db_server) . $query);

                //if there are any rows, print out the contents
                if ($row = mysqli_fetch_array($result)) {

                    //Whether to display links or not for purchase and streaming
                    $filmID = $row['filmID'];

                    //Body content for film             
                    $str_result = 
                    "<section> This is where the film details are
                       </section>"
                       . $commentMessage . "
                       <section>
                        <form id='frmFilmComments' action='index.php?filmID=" . $filmID . "#comments' method='post'>
                            <a id='comments' class='anchor'></a>
                            <h3>Comments</h3>
                            <p><span class='bold'>Did you like " . $row['filmName'] ."?</span></p>
                            <select class='selectbox' name='yesornoList'>
                                <option value='Yes'>Yes</option>
                                <option value='No'>No</option>
                            </select>
                            <p><span class='bold'>Provide your feedback here:</span></p>
                            <textarea id='commentBox' class='insertComment' rows='2' cols='30' name='commentBox'></textarea><br>
                            <input class='formButton' type='submit' id='submit' name='submit' value='Submit comment'/>
                        </form>
                        ";

                    mysqli_free_result($result);

                    //Code to print comments goes here

                }else{
                    $str_result = "<section><h3>Sorry</h3><p>We couldn't find any films that match your terms. </br> <a href='#findafilm'>Please try again.</a></p></section>";
                }

            }else{
                    //$str_result = "<section><h3>Sorry</h3><p>No genre was chosen.</br><a href='home.php'>Please try again.</a></p></section>";        
            }

            $message = $str_result . $likedcomments . $dislikedcomments . "<section/>";
        }

    }

    //Exisiting code to handle options list

?>

            <div id="top" class="content container headerMargin">
                <div class="content wrapper">          

                   <form id="frmFilmFinder" action="index.php?filmID=<?php echo $filmID; ?>" method="post">
                       <section>
                         <h2>Welcome <?php echo $_SESSION['username'] ?>!</h2>
                         <p class="underHeader">You are now logged in and ready to use the Film Finder.</p>
                       </section>
                       <section>
                           <a class="anchor" id="findafilm"></a>
                           <h3>Find a film</h3>
                           <h4>Choose a genre:</h4>
                           <select class="selectbox" name="genreList">
                               <?php echo $str_options; ?>
                           </select>
                           <h4>Choose a streaming service:</h3>
                            <input type="checkbox" class="checkbox" id="streamingCheckbox1" name="streamingCheckbox1" value="Netflix"><span class="checkboxText">Netflix</span><br>
                            <input type="checkbox" class="checkbox" id="streamingCheckbox2" name="streamingCheckbox2" value="LoveFilm"><span class="checkboxText">LoveFilm Instant</span><br>
                            <input type="checkbox" class="checkbox" id="streamingCheckbox3" name="streamingCheckbox3" value="blinkbox"><span class="checkboxText">blinkbox</span><br>
                            <input type="submit" class="formButton filmSearch" id="submit" name="submit" value="Submit"/>
                            <p><span class="italic">Leave all unticked if you wish to buy the film</span></p>
                        </section>
                        </form> 
                        <?php echo $message; ?>
                </div>
            </div>
jb93
  • 77
  • 8
  • @MichaelBerkowski Sure sorry, hang on a sec – jb93 Jan 04 '14 at 19:55
  • @MichaelBerkowski there we go – jb93 Jan 04 '14 at 19:59
  • Well `$_GET['filmID']` is for when the comment submit button is pressed. I assumed that I needed to echo this row out in the main form process to use it for the GET process when a comment is pressed? – jb93 Jan 04 '14 at 20:05
  • Well I echoed the errors you suggested and got ` 24567 ` Not too sure what that means? Well on page load it's simply index.php. Is there no way to get this filmID in the URL on submission? – jb93 Jan 04 '14 at 20:10
  • I tried `var_dump($row)` and it came back with NULL. What does this mean? I don't have any mod_rewrites, I'm not quite sure what they even are to be honest – jb93 Jan 04 '14 at 20:19
  • Right these are the errors I got back that might be causing trouble: `Notice: Undefined index: submit in index.php on line 27` – jb93 Jan 04 '14 at 20:22
  • I've changed the submission line, thank you! Right I see, so there's something going on that's preventing my filmID from appearing in the main form's URL? I just think it's strange that it works for the comments form but not the main one – jb93 Jan 04 '14 at 20:29
  • I would use the GET method for the main form's action but there's a lot in there and I don't think it's very user-friendly - all I really want there is the film's ID – jb93 Jan 04 '14 at 20:35
  • I kinda see what your problem is now - you're only populating `$formID = $_GET['formID']` from the comment submission form. Move that _above_ any `if()` conditions. `$filmID = isset($_GET['filmID']) ? $_GET['filmID'] : null;` Or store it in `$_SESSION` if you're using that. – Michael Berkowski Jan 04 '14 at 20:39
  • Would the randomising process be affected is I put it in the session? I stuck `$filmID = isset($_GET['filmID']) ? $_GET['filmID'] : null;` and commented out the current get method, unfortunately with no change – jb93 Jan 04 '14 at 20:47
  • I understand what you mean but it only populating from the comment submission form, I'm really not sure what could be going wrong here though – jb93 Jan 04 '14 at 20:58
  • `$filmID` looks only ever to ever have a value when the comment form is displayed. I suggest storing it to `$_SESSION` at the time you do `$filmID = $row['filmID']` and reading it from there. Be sure to unset it when you don't want it and it shouldn't interfere with anything else. This is otherwise just down to debugging, inspecting var values at different points, and I can't help with that. – Michael Berkowski Jan 04 '14 at 21:13
  • Right now when I submit, still nothing, if I submit again then it appears in the URL? If I manually type in the URL, it's just index.php and the main form – jb93 Jan 04 '14 at 21:27
  • This occurs whether or not it's stored in a session. In terms of SQL injection I'll probably be adding more clean_string()s once I've got these issues sorted – jb93 Jan 04 '14 at 21:33
  • Hey I've managed to sort of get it working now thanks to your help, I added your `isset($_GET['filmID']) ? $_GET['filmID'] : null;` within my clean_string() function and I now have an if statement to display film data if the ID is in the URL. I think I might have to abandon ship on adding the ID to the main form. If you want to add a an answer to this question I'll mark it as the answer. Thanks again for your help! – jb93 Jan 05 '14 at 14:03

1 Answers1

1

Principally, you need to be sure that $filmID is set when you write out your forms. It is valid to pass it in the query string (accessible via $_GET['filmID'] even though you are posting the form. It will work and serve its purpose, but be sure to comment what you're doing and why so you remember next time.

You populate it as $filmID = $_GET['filmID'] but only inside the form processing for your comments form. That means it won't be set unless you're receiving a comment. You ought to move that higher in the logic, checking always if it is set.

// near the top, outside if() conditions:
$filmID = isset($_GET['filmID']) ? $_GET['filmID'] : null;

Consider storing it into $_SESSION['filmID'] the first time you set it and any time it changes, so you have it on any script that needs it.

Finally, a side issue mentioned in the comments thread, working with MySQLi is a start, begin familiarizing yourself with how prepared statements work with bound parameters via mysqli::prepare(). All your query input variables should be handled via bound parameters, eliminating the need for escaping. This is a general best practice.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390