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.
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();
}
});
});
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:
Note common things
Note differences, e.g. different values passed to same pieces of code
Move differences to variables before common things
Now you can easily transform piece of code into a function -- just make a function with things from p.3 as parameters
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.
Related
I need to remove the blank option.
This is a restaurant web page and this is the reservation form.
The thing is that they are reciving a lot of "blank" reservation hours because people don't specify the reservation hour.
Sorry for my English, I'm from Spain :)
The code:
HTML read by browser
<div id="lashoras">
<select name="Hora" size="1" onChange="updateHoraPersonas();">
<option value="" selected="selected"> </option>
<option value="1330">13:30</option>
<option value="1400">14:00</option>
<option value="1430">14:30</option>
<option value="1500">15:00</option>
<option value="1930">19:30</option>
<option value="2000">20:00</option>
<option value="2030">20:30</option>
<option value="2100">21:00</option>
<option value="2130">21:30</option><option value="2200">22:00</option></select>
</div>
source code HTML
<div id="lashoras">
<?php
echo $selectFullDay;
?>
SelectFullDay PHP Var
$selectFullDay = build_select_options ("Hora","id_lookup","lookup","lookups",0," ",$onChange,$theWhere,$multiple,$orderby);
updateHoraPersonas Function
function updateHoraPersonas(){
var mediodiaMax = maxPersonas;
var nocheMax = maxPersonas;
mediodiaMax = maxPersonas-curDia_mediodia_reservados;
if(mediodiaMax<0) mediodiaMax = 0;
nocheMax = maxPersonas-curDia_noche_reservados;
if(nocheMax<0) nocheMax = 0;
var hora = $('#lashoras').val();
//hora blank for first, otherwise 1330
//primero ver si llegado a tope de mediodia/noche
if (hora <= horaCambio) {
selectMax = mediodiaMax;
} else {
selectMax = nocheMax;
}
//y ahora hora a hora
selectMax = Math.min(selectMax,horasArray[hora]);
var Numero_de_personasSelect = "";
for (i=1 ; i<= selectMax ; i++) {
if (i==1) {
selected = "selected='selected'";
} else {
selected = "";
}
Numero_de_personasSelect += "<option value='"+i+"' "+selected+" >"+i+"</option>";
}
if (selectMax <=0 ) {
Numero_de_personasSelect += "<option value=''>Completo</option>";
}
$("#Numero_de_personas").html(Numero_de_personasSelect);
//alert('mediodiaMax: '+mediodiaMax+' | nocheMax: '+nocheMax+' | selectMax: '+selectMax);}
</script>
....
Change the form submission so that the user cannot submit if the reservation time is not specified! This way you processing time does not increase on explicitly removing blank options
an exapmle
<?php
if(!isset($_POST['time'])){
//'Enter valid details
}else{
//redirect here
}
I use bootstrap selectpicker to select multiple options.
Code is:
<select id="product_parent_id" class="selectpicker" size="1" name="product_parent_id[]" multiple data-selected-text-format="count">
<?php
foreach ($result_cat as $key => $cat) {
$cat_name='';
if($cat->category_parent_id!=0) {
$cnt=0;
$cat_name='';
$r_cat=$cat->category_parent_id;
do {
$cnt++;
$qur='SELECT category_parent_id FROM #__virtuemart_category_categories WHERE id='.$r_cat;
$db->setQuery($qur);
$r_cat=$db->loadResult();
} while($r_cat!=0);
for($i=0;$i<$cnt;$i++) {
$cat_name=$cat_name.'-';
}
$cat_name=$cat_name.$cat->category_name;
} else {
$cat_name=$cat->category_name;
}
$sel_c='';
if(in_array((string)$cat->id,$sel_cat_arr)) {
$sel_c='selected="true"';
}
?>
<option value="<?php echo $cat->id;?>" <?php echo $sel_c;?>><?php echo $cat_name;?></option>
<?php
}
?>
</select>
I downloaded bootstrap-selectpicker.zip
I use cdn: bootstrap-select.css,bootstrap-select.js
The selectpicker works in normal html page but in joomla select box it is not displayed. I found conflicts, but didn't get the solution.
Check if this works,
<?php
foreach ($result_cat as $key => $cat) {
$cat_name='';
if($cat->category_parent_id!=0)
{
$cnt=0;
$cat_name='';
$r_cat=$cat->category_parent_id;
do{
$cnt++;
$qur='SELECT category_parent_id FROM #__virtuemart_category_categories WHERE id='.$r_cat;
$db->setQuery($qur);
$r_cat=$db->loadResult();
}while($r_cat!=0);
for($i=0;$i<$cnt;$i++)
{
$cat_name=$cat_name.'-';
}
$cat_name=$cat_name.$cat->category_name;
}
else
{
$cat_name=$cat->category_name;
}
$sel_c='';
if(in_array((string)$cat->id,$sel_cat_arr))
{
$sel_c='selected="true"';
}
echo '<option value=\"'.$cat->id.'">'.$cat_name.'</option>';
?>
This is coming from my form field :
$subject="physics with maths";
This is in my database :
$keywordsindatabse="(physics && electronics) || (electronics & communication) || (electronics and communication)";
On submission of form I want to match the condition $keywordsindatabse with $subject.
Any Ideas?
Any help will be appreciated.
Code:
<form id="myform" name="myform">
<select name="sselect" id="itmn">
<option value="">Select</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
</select>
<input type='text' name='gmajorsub' id=""" value="" onblur="chkdegree(document.getElementById('itmn').value,this.value);">
</form>
<script>
function chkdegree(item_id,keyword)
{
$.ajax({
type: "GET",
url: "degree_match.php",
dataType: 'html',
data: {item_id : item_id,keyword : keyword},
success: function(data){
if(data=="0")
{
alert("Dear Applicant, You are not allowed to register.You Subject not matching our essential qualification requirements.");
document.getElementById("gmajorsub").value="";
document.getElementById("gmajorsub").focus();
return false;
}
}
});
}
</script>
degree_match.php:
<?php
include("../../lib/dbc/dbConnection.php");
require('../../lib/dbc/commonFunc.php');
require('../../lib/dbc/dbHandler.class.php');
$dbObject = new dbHandler();
$dbObject->connect();
$query="select * from advt_110_post_details where recNo='".$_REQUEST['item_id']."'";
$result=mysql_query($query);
$num=mysql_fetch_array($result);
$keyword=strtolower($_REQUEST['keyword']);
$degree=$num['subject_keywords'];
$degree1=explode("|",$degree);
$max = array(null, 0); // category, occurences
/*foreach($degree1 as $k => $v) {
$replaced = str_replace($v, '##########', $keyword);
preg_match_all('/##########/i', $replaced, $matches);
if(count($matches[0]) > $max[1]) {
$max[0] = $k;
$max[1] = count($matches[0]);
}
}
if($max[1]>=count($degree1))
{
echo"1";
}
else{
echo"0";
}
*/
/*foreach($degree1 as $k => $v) {
if ( strstr( $membership, "member" ) )
{
}
}
*/
?>
Note: You're code is subject ot SQL injection. Look at using PDO prepared statements or mySQLi prepared statements. At the very least, wrap string input into hte database in mysql_real_escape_string.
Looking at your code, you're getting items from a database and then filtering. I'm assuming mySQL.
You might be better doing this withing the database end. Check out "full text search". This only works with MyISAM tables, so change that if needed. Then add a FullText index to the table on the 'subject_keywords' and you'll need to set up a boolean seaerch using full text. Details on the boolean search are here.
(Failing that, Rishi's answer above has introduced the loops you need - that was missing from your attempt.)
As far as i understood from your post, the below code might help..
$subject="physics with maths";
$keywordsindatabse="(physics && electronics) ||
(electronics & communication) ||
(electronics and communication)";
$pieces = explode(" ", $subject);
$piecesDB = explode("||", $keywordsindatabse);
$subsDBv=array();
foreach($piecesDB as $key=>$subsDB){
$subsDBv[$key] = str_replace(array("(",")"),"",explode(" ", $subsDB));
}
foreach($subsDBv as $subslvd){
foreach($subslvd as $subslv){
$ao = next($subslvd);
foreach($pieces as $subs){
if((strpos($subslv,$subs) !== false) AND (strpos($ao,$subs) !== false)){
echo "Match found..<br />";
}
else{
echo "Sorry, no match found..<br />";
}
}
}
}
In my view I have the following select menu that states what type of form types are available:
<label for="add_fields_type">Type: </label>
<select name="add_fields_type" id="add_fields_type">
<option value="input">Input</option>
<option value="textarea">Text Area</option>
<option value="radiobutton">Radio Button</option>
<option value="checkbox">Check Box</option>
</select>
In my controller I currently have the following but I am unsure how to make is so that if $_REQUEST['add_fields_type'] is = to lets say radiobutton then it will display that respective code.
Controller:
if (isset($_REQUEST['add_fields_type']))
{
echo $_REQUEST['add_fields_type'];
}
if (isset($_REQUEST['add_fields_type'])) {
if ($_REQUEST['add_fields_type'] == 'input') {
// echo stuff for input
}
else if ($_REQUEST['add_fields_type'] == 'textarea') {
// echo stuff for textarea
}
else if ($_REQUEST['add_fields_type'] == 'radiobutton') {
// echo stuff for radiobutton
}
else if ($_REQUEST['add_fields_type'] == 'checkbox') {
// echo stuff for checkbox
}
}
Another way, using the switch code that swapnesh mentioned (slightly more concise than having multiple if statements and will stop when it hits the right case):
if (isset($_REQUEST['add_fields_type']))
{
switch($_REQUEST['add_fields_type'])
{
case('input'):
// echo stuff for input
break;
case('textarea'):
// echo stuff for textarea
break;
case('radiobutton'):
// echo stuff for radiobutton
break;
case('checkbox'):
// echo stuff for checkbox
break;
default:
// echo stuff if the other cases fall through
break;
}
}
Using select and option HTML tags, I pass information through using $_POST.
When reloading the page however, the select resets back to the original values.
I am looking to get it to remember what has been passed through.
<?php
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
echo"<option value='$value-$first-$second'>$title - $first - $second</option>";
}
}
}
?>
As you can see, I use 3 foreach loops to populate whats in it.
How can I achieve my selection being remembered?
Thanks for reading.
You'll need to use the name of your select field in place of "your_select_field_name" in my change below:
<?php
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
echo "<option value='$value-$first-$second'";
if( $_POST['your_select_field_name'] == "$value-$first-$second" ) {
echo ' selected="selected"';
}
echo ">$title - $first - $second</option>";
}
}
}
?>
The output for the selected option on the new page needs to look like:
<option value='foo' selected>...<option>
HTML does not have memory. The item that's selected by default in a <select> form element is the one with the selected attribute (or the first one if none). Simply use the information contained in $_POST to generate the appropriate markup:
<select name="foo">
<option value="v1">Label 1</option>
<option value="v2">Label 2</option>
<option value="v2" selected="selected">Label 3</option>
<option value="v4">Label 4</option>
</select>
You need to set the selected tag on the correct option. Something like this:
<?php
$postedValue = $_POST['select_name'];
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
$computedValue = $value . '-' . $first . '-'. $second;
if ( $computedValue == $postedValue) {
$selected = "selected";
} else {
$selected = ''
}
echo "<option value='$computedValue' $selected>$title - $first - $second</option>";
}
}
}
?>
It could probably be written cleaner but this is the general idea.