Jump to content

PHP Variable Variables & Loops with Forms


Go to solution Solved by gizmola,

Recommended Posts

Hi All,

PHP newbie here.

Getting to grips with various aspects of learning PHP however i seem to have hit a bit of a stumbling block.

The below code loops through my $available_games (foreach from what i have read is the best way to do this) and outputs a nice table. Users then click on the Sign Up button where they input some details in a form to signup.

I am displaying the value from the hidden input box (name="game_name") on the next page so i know what game they have signed up for and can insert this into the database.

However currently this only displays the final $available_games['game_name'] in the list (ie if there are 2 available it always shows the 2nd, even if they select the 1st available game - there could be more than 2 but in my test example i am using 2)

I want the <input type="hidden" name="game_name" value="<?php echo $available_games['game_name']?>"/> value to be the correct one depending on where in the loop of $available_games it is at. (Ie 1st available game then keep this value and display on the next page - if 2nd is chosen then use this etc etc)

 I have looked at producing a variable variable in a loop but couldn't get this to work. Any help is appreciated.


     

        foreach($available_games as $available_games) {

        echo "<tr>";
        echo "<td>";
        $game_name = $available_games['game_name'];
        $_SESSION['game_name'] = $game_name;
        echo "<center>" . $game_name . "</center>";
        echo "</td>";
        echo "<td>";
        echo "<center>" . $available_games['speed_modifier']  . "</center>";
        echo "</td>";
        echo "<td>";
        $open = strtotime($available_games['open_date']);
        $open_date = date("d-m-Y H:i", $open);
        echo "<center>" . $open_date  . "</center>";
        echo "</td>";
        echo "<td>";
        $close = strtotime($available_games['close_date']);
        $close_date = date("d-m-Y H:i", $close);
        echo "<center>" . $close_date  . "</center>";
        echo "</td>";
        echo "<td>";
        
        ?>

        <input type="hidden" name="game_name" value="<?php echo $available_games['game_name']?>"/>   

        <form action="signup.php" method="POST">
        <input type="submit" name="signup" value="Sign Up"/>
        
        <?php
        echo "</td>";
        echo "</tr>";
        }
        
        echo "</table>";

 

Link to comment
https://forums.phpfreaks.com/topic/314390-php-variable-variables-loops-with-forms/
Share on other sites

First obvious bugs:

foreach($available_games as $available_games) {

Your as needs to be a variable you will use inside the foreach loop.  You are re-assigning the array variable.  I would just use $game:

foreach($available_games as $game) {

Then use $game to access the data inside the foreach. Remove all the references to $available_games and replace with $game['the_array_key'].

Remove the $_SESSION setting of game.  All you are doing is setting/resetting that value on the server when you generate output.  It is not helpful for you in this case.

Remove $game_name = $available_games['game_name'];  Just use $game['game_name'].

An important concept to be clear on is how HTTP works.    You want to have high familiarity with the REQUEST -> RESPONSE nature of HTTP and the type of Requests that are possible, as well as what actually happens.  Chrome devtools  - network tab are a great way of exploring this.

In your case it's something like this:

  1. User issues GET request to server for page with list of games.  Gets RESPONSE HTML.
  2. At this point, nothing else happens on the server until another request.  That could be from the form on your page, or not, but in any case, what comes next requires an "event" from the client to the server.

In other words, once the client has the html/css/javascript, there is no longer a way for you to do PHP manipulation without another request/response.  

Hopefully this illustrates to you, that you need javascript to set the game_name value.

Personally, what I would suggest is this:

  • Add a Modal dialog.  CSS frameworks like Bootstrap make this very modular and easy to do, but the basic idea is that your entire form is in a div that has display: none.
  • In your foreach loop output a button with "signup for this game" or whatever you like, as the text.
  • Give all the buttons a css class name like "btn_game_signup".
  • Include a data_ attribute for the buttons that have the game_id or game_name, in this attribute.  An id would be better, but that depends on your database design.  Either way it's the value you need in your signup.php to identify the game the person is signing up for.

Something like this:

echo "<button class='btn_game_signup' data_game='{$game['game_name']}'>Signup for this game</button>";

At the point you have this working, you will need to write a javascript function that does the following:

  • Sets the hidden attribute of the form = to the data_game value from the clicked button
  • Makes the signup form visible

You will need a couple of click event handlers:

  • On the hidden form, you need a handler for the submit button that resets the form div display to none after the form is submitted.
  • Your 'btn_game_signup' class needs a click event handler assigned, that calls function I described previously.

 

In summary:

  1. Fix your foreach loop variables
  2. Add the css and html for your hidden form.  The form will be displayed when a game signup is clicked
  3. Add javascript to the end of the page that add the event handlers you need. 

Here's a little snippet to give you one way of setting up your click event handler for the game buttons.  You would need to flesh out "yourFunction" as described above, but this gives you a headstart to test with.

const elements = document.getElementsByClassName("btn_game_signup")

const yourFunction = function() {
    let attribute = this.getAttribute("data-game")
    alert(attribute)
}

for (let i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', yourFunction, false)
}

 

Hi Gizmola,

Thank you for the concise reply - I will take a look at this tomorrow and see if I understand and can learn what you have suggested.

Currently once the user clicks the button on the page it takes them to signup.php which has a form with the game details on it - apologies if I didn't make this clear. Its getting late and i'm getting sleepy. Been trying to solve this for a few days but finally bit the bullet after numerous failures. Should've done it sooner!

Have read another post on here about moving away from the mysqli_ commands so just doing some learning on PDO atm :)

Edited by lost4words
  • Solution

No worries - we all agree on using PDO so that is a good investment of your time.

If you want to goto a new page that just has the signup form, then have all the buttons in the game list inside anchor tags.  Then you can just pass the game_name as a url parameter to the page that generates the form.  The signup page can just set the hidden game attribute using the $_GET parameter.

I personally would opt for the usability of not having a separate signup form, but if it's simpler for you to go from a->b->c and get things working that way, do that then.  It makes the javascript event stuff simpler, although you will definitely need to learn that sooner than later.  I like Scrimba as a platform to learn html/css/javascript concepts, although there are many other freemium platforms.  Freecodecamp also does a good job.

Simpler solution for you, again rendered buttons inside your foreach loop that lists the games (ie. one button per game listed):

echo "<a href='signup.php?game_name=\"{$game['game_name']}\"'><button class='btn_game_signup'>Signup for this game</button></a>";

Clicking on the signup page will send a GET request to your signup.php script, which will include the $_GET parameter of 'game_name'.

Then you just set the hidden form attribute of that page in your signup.php script to the value of $_GET['game_name'].

Mysqli was definitely easy to get the handle of (although the old video i was learning from was mysql so had to figure out the latest techniques) but if PDO is the 'standard' happy to get to grips with this and would rather do it at this point when I'm starting out, rather than when I'm a while down the road and its harder to get rid of the bad habit!

7 minutes ago, gizmola said:

Simpler solution for you:

echo "<a href='signup.php?game_name=\"{$game['game_name']}\"'><button class='btn_game_signup'>Signup for this game</button></a>";

 

Sometimes a simple solution is great - I understand what this is doing although I have read that putting stuff in the url is not the most secure method as it takes away the 'hidden' aspect.
Although I would like to spend some time learning Javascript if this would be useful. Only been learning PHP for a couple of weeks on and off so far.

Therefore the a>b>c method is the easiest for me currently, however if there is a better way (albeit may take some more learning) then I'm up for doing it.

My work has a 'Pluralsight' subscription so will see what that has available for Javascript. I have a basic handle of HTML from ages ago but also need to understand css eventually, not too fussed about graphics etc more interested in how the nuts and bolts work behind the scenes currently!

I am doing all of this for fun - mainly to see if I can emulate/reproduce a text based game that I used to play when I was younger but now seems to have died :(

Where would you recommend learning about versioning? (currently i am copying old versions into notepad++ but would like to be able to easily back out changes etc once my project gets bigger!)

So, considering you also need to learn css, definitely make a scrimba account. They have free courses there on css from Kevin Powell who is a css authority and excellent teacher.  Even if you decide to get a pro membership, it's pretty economical.  The scrimba platform makes it easy to do the exercises without having to setup your own environment, but you can take code from it and use it in a "real" website setup.

For source code management, use git.  Git is pretty much the world standard for source code management now.  Pluralsight has a course on it, but I can't vouch for it, but as you have the resource check it out.  You also want to make a github account, which you can use to make repos for your projects.  You can then setup your local git to use your github account as a remote and push your code there.  

I have done some git presentations in the past, and although it's just the slides, it might help you get a jumpstart on learning it.  I can't say how long I'll leave this here, but for now there's a link to presentation converted to pdf.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.