1

I'm working on a school project and i need some suggestions. It is a HTML/PHP/SQL project where users can give their input about gaming experiences. As an admin you have to be able to see the names of the users that chose for certain gaming categories. This needs to be showed in tables using PHP and MySQL.

I have now finished this page, it is working like a charm and i can see all the users input. But the problem is that i have about 600 lines of code since i have 12 different div's with MySQL statements and tables.

Currently my code is seperated into 3 parts, the html select dropdown, 12 different div's with query's that generates tables, and jquery to show / hide the tables based on the select dropdown

I am hoping someone could give me a suggestion on how to shorten my code, since 600 lines of code is crazy and i am aware that it could be shorter but i just can't figure out how.

This is what it looks like right now The HTML Select:

<select name="type" id="type" style="margin-left:57px; width:153px;">
        <option name="select" value="select">Selecteren..</option>
        <optgroup label="Hoe spelen mensen?">
            <option name="alleen" value="alleen">Meestal alleen</option>
            <option name="fysiek" value="fysiek">Meestal samen fysiek</option>
            <option name="online" value="online">Meestal samen online</option>
        </optgroup>
        <optgroup label="Categorieën bordspellen">
            <option name="alleen" value="kaartspellen">Kaartspellen</option>
            <option name="fysiek" value="strategische">Strategische bordspellen</option>
            <option name="online" value="fantasy">Fantasy bordspellen</option>
            <option name="online" value="klassiek">Klassieke gezelschapspellen</option>
        </optgroup>
         <optgroup label="Categorieën computergames">
            <option name="alleen" value="sport">Sport games</option>
            <option name="fysiek" value="adventure">Adventure games</option>
            <option name="online" value="war">War games</option>
            <option name="online" value="strategischegames">Strategische games</option>
        </optgroup>
        <optgroup label="Gebruikers">
            <option name="alle" value="alle">Alle gebruikers</option>
        </optgroup>

1 div with a table (as example, since there are 12 different of these)

<div class="row" id="wargames">
<?php
$war = "SELECT * FROM form where categorie = 'wargames'";

$querywar = mysqli_query($conn, $war);

if (!$querywar) {
    die('SQL Error: ' . mysqli_error($conn));
}
?>
   <table class="data-table">
    <caption class="title">Deze mensen spelen meestal de categorie War 
    games</caption>
    <thead>
        <tr>
            <th>Naam</th>
            <th>Woonplaats</th>
            <th>E-mail</th>
        </tr>
    </thead>
    <tbody>
    <?php

while ($row = mysqli_fetch_array($querywar)) {
echo '<tr>

                <td style="text-align:center">' . $row['naam'] . '</td>
                <td style="text-align:center">' . $row['woonplaats'] . 
                 '</td>
                <td style="text-align:center">' . $row['email'] . '</td>
            </tr>';
}
?>
 </tbody>
</table>

my jquery

$(function() {
$('#row_dim').hide(); 
$('#type').change(function(){
    if($('#type').val() == 'alleen') {
        $('#alleen').show(); 
    } else {
        $('#alleen').hide(); 
    } 
    if($('#type').val() == 'fysiek') {
        $('#fysiek').show(); 
    } else {
        $('#fysiek').hide(); 
    } 
    if($('#type').val() == 'online') {
        $('#online').show(); 
    } else {
        $('#online').hide(); 
    } 
    if($('#type').val() == 'kaartspellen') {
        $('#kaartspellen').show(); 
    } else {
        $('#kaartspellen').hide(); 
    } 
    if($('#type').val() == 'strategische') {
        $('#strategische').show(); 
    } else {
        $('#strategische').hide(); 
    }
    if($('#type').val() == 'fantasy') {
        $('#fantasy').show(); 
    } else {
        $('#fantasy').hide(); 
    }
    if($('#type').val() == 'klassiek') {
        $('#klassiek').show(); 
    } else {
        $('#klassiek').hide(); 
    }
    if($('#type').val() == 'sport') {
        $('#sportgames').show(); 
    } else {
        $('#sportgames').hide(); 
    }
     if($('#type').val() == 'adventure') {
        $('#adventure').show(); 
    } else {
        $('#adventure').hide(); 
    }
     if($('#type').val() == 'war') {
        $('#wargames').show(); 
    } else {
        $('#wargames').hide(); 
    }
    if($('#type').val() == 'strategischegames') {
        $('#strategischegames').show(); 
    } else {
        $('#strategischegames').hide(); 
    }
    if($('#type').val() == 'select') {
       $('#selected').show();
    } else {
        $('#selected').hide();
    }
    if($('#type').val() == 'alle') {
       $('#gebruikers').show();
    } else {
        $('#gebruikers').hide();
    }

});
 $( document ).ready(function() {
 if($("#type").attr("selectedIndex") !== 0) {
    $('#selected').show();
    $('#strategischegames').hide();
    $('#wargames').hide(); 
    $('#adventure').hide(); 
    $('#sportgames').hide(); 
    $('#klassiek').hide();
    $('#fantasy').hide(); 
    $('#strategische').hide(); 
    $('#kaartspellen').hide(); 
    $('#online').hide(); 
    $('#fysiek').hide(); 
    $('#alleen').hide(); 
    $('#gebruikers').hide(); 
}

});
});

1 Answer 1

1

One think to shorten would be $('#type').change(...) handler:

$('#type').change(function () {
    const map = {
        'alleen': 'alleen',
        'fysiek': 'fysiek',
        'online': 'online',
        'kaartspellen': 'kaartspellen',
        'strategische': 'strategische',
        'fantasy': 'fantasy',
        'klassiek': 'klassiek',
        'sport': 'sportgames',
        'adventure': 'adventure',
        'war': 'wargames',
        'strategischegames': 'strategischegames',
        'select': 'selected',
        'alle': '#gebruikers',
    };

    Object.keys(map).forEach(key => {
        if ($('#type').val() == key) {
            $('#' + map[key]).show();
        } else {
            $('#' + map[key]).hide();
        }
    });
});

As you can see, I declaratively map values to IDs, then process all of them in a cycle.

Next step would be generalizing that show/hide functionality:

function show(type) {
    const map = {
        'alleen': 'alleen',
        'fysiek': 'fysiek',
        'online': 'online',
        'kaartspellen': 'kaartspellen',
        'strategische': 'strategische',
        'fantasy': 'fantasy',
        'klassiek': 'klassiek',
        'sport': 'sportgames',
        'adventure': 'adventure',
        'war': 'wargames',
        'strategischegames': 'strategischegames',
        'select': 'selected',
        'alle': '#gebruikers',
    };

    Object.keys(map).forEach(key => {
        if (type == key) {
            $('#' + map[key]).show();
        } else {
            $('#' + map[key]).hide();
        }
    });
}

With that function, your change and ready event handlers can be shortened like this:

$('#type').change(function () {
    show($('#type').val());
});

$(document).ready(function () {
    if ($("#type").attr("selectedIndex") !== 0) {
        show('select');
    }
});

Re PHP part, I see only one piece, so, I don't know what is common with others, but as a general rule:

  1. Note common things
  2. Note differences, e.g. different values passed to same pieces of code
  3. Move differences to variables before common things
  4. Now you can easily transform piece of code into a function -- just make a function with things from p.3 as parameters
  5. Call that function as many times as needed, or maybe in a loop -- this is exactly what I did with your JS code at the top of my answer

And, of course, your HTML screams "extract data structure from me and format it into tags". In other words, separate data from presentation, e.g.:

<?php
$data = [
    [
        'value'           => 'select',
        'text'            => 'Selecteren..',
        'childrenCaption' => 'Hoe spelen mensen?',
        'children'        => [
            'alleen' => 'Meestal alleen',
            'fysiek' => 'Meestal samen fysiek',
            'online' => 'Meestal samen online',
        ],
    ],
];

function formatOptions($data) {
    foreach ($data as $section) {
        echo "<option name=\"$section[value]\" value=\"$section[value]\">$section[text]</option>\n";
        echo "<optgroup label=\"$section[childrenCaption]\">\n";
        foreach ($section['children'] as $value => $text) {
            echo "    <option name=\"$value\" value=\"$value\">$text</option>\n";
        }
        echo "</optgroup>\n";
    }
}

formatOptions($data);

And sample output looks like this:

<option name="select" value="select">Selecteren..</option>
<optgroup label="Hoe spelen mensen?">
    <option name="alleen" value="alleen">Meestal alleen</option>
    <option name="fysiek" value="fysiek">Meestal samen fysiek</option>
    <option name="online" value="online">Meestal samen online</option>
</optgroup>

As you can see, modifying $data variable is much easier than maintaining that much of HTML code.

There is more room from improvement, but this is a good start, I guess.

Sign up to request clarification or add additional context in comments.

1 Comment

As I have said in the middle of the answer, I can't show you exact changes because I don't see all 12 code snippets. All I can do is general advice which is already in the answer, see section starting with "Re PHP part". If it is not clear what I'm saying, you could paste another div code in your question, and with two samples we can work out differences and similar parts to refactor it into a function.

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.