-4

So, I'm working on a mask which filters the data when <input type="button" /> is clicked.

I have:

  • school classes(1, 2, 3, 4, 5)
  • sections (A, B, C....Z)
  • and sex checkboxes (male, female).

This mask interacts with a mysql database, so if the only one checkbox checked is "male", it should give me back all the males in my database. The problem is that I used javascript to filter sexes and to make my string of sexes and I don't know how to pass it to a php variable to use it on my query.

I've been looking online for 3-4 days and all recommend to use $_POST. If I use $_POST it says that the variable is undefined. I searched for this error on the internet and it says to add a control with isset. I've done this but nothing seems to work because it gives me a new error "undefined index".

So I need help for passing the value of a javascript variable to a php variable (I know it's hard because javascript is client side and php is server side) or directly pass my textarea text (I can display my javascript result in a textarea) to a php variable.

May someone help me?

Here is my index.php:

<?php
require 'connection.php'
?>

<html>
<script src="scripts.js"></script>

<form name="code" method="post" action="query.php; <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
   <table border="0">
<!-- ROW1 -->
 <tr>


  Da codice 
  <input type="text" name="dacode">

   a codice 
  <input type="text" name="acode">


        </tr>

        </form>     

<!-- ROW2 -->   
        <form id="sexform" name="sexform">  
        <tr>
          <td></td>
          <td>

Sesso
<input type="checkbox" name="sex" value="Maschio"> M
<input type="checkbox" name="sex" value="Femmina"> F
<input type="checkbox" name="sex" value="Azienda"> G
<input type="hidden"  id="xxx">
        </form>
<!-- ROW3 -->
<br>
  Da data nascita
  <input type="date" name="dadata" min="1980-01-01">


  a data nascita
  <input type="date" name="adata" min="1980-01-01">

<!-- ROW4 -->
<form id="sezform" name="sezform">
<br>
Sezioni
<input type="checkbox" name="sez" value="A"> A
<input type="checkbox" name="sez" value="B"> B
<input type="checkbox" name="sez" value="C"> C
<input type="checkbox" name="sez" value="D"> D
<input type="checkbox" name="sez" value="E"> E
<input type="checkbox" name="sez" value="F"> F
<input type="checkbox" name="sez" value="G"> G
<input type="checkbox" name="sez" value="H"> H
<input type="checkbox" name="sez" value="I"> I
<input type="checkbox" name="sez" value="J"> J
<input type="checkbox" name="sez" value="K"> K
<input type="checkbox" name="sez" value="L"> L
<input type="checkbox" name="sez" value="M"> M
<input type="checkbox" name="sez" value="N"> N
<input type="checkbox" name="sez" value="O"> O
<input type="checkbox" name="sez" value="P"> P
<input type="checkbox" name="sez" value="Q"> Q
<input type="checkbox" name="sez" value="R"> R
<input type="checkbox" name="sez" value="S"> S
<input type="checkbox" name="sez" value="T"> T
<input type="checkbox" name="sez" value="U"> U
<input type="checkbox" name="sez" value="V"> V
<input type="checkbox" name="sez" value="W"> W
<input type="checkbox" name="sez" value="X"> X
<input type="checkbox" name="sez" value="Y"> Y
<input type="checkbox" name="sez" value="Z"> Z
<br>
<input type="checkbox" name="sez" value="Ai"> Ai
<input type="checkbox" name="sez" value="Am"> Am
<input type="checkbox" name="sez" value="Ae"> Ae
<input type="checkbox" name="sez" value="Bi"> Bi
<input type="checkbox" name="sez" value="Be"> Be
<input type="checkbox" name="sez" value="Bm"> Bm

        </form>
<!-- ROW5 -->
<form id="claform" name="claform">
<br>
Sezioni
<input type="checkbox" name="cla" value="1"> 1
<input type="checkbox" name="cla" value="2"> 2
<input type="checkbox" name="cla" value="3"> 3
<input type="checkbox" name="cla" value="4"> 4
<input type="checkbox" name="cla" value="5"> 5

 <br>
 <br>
 RESULT STRING

  <textarea type="text"  name="outputfield" id="outputfield"> </textarea>
 <input type="button" onclick="myFunction(); selectValues(); query();" value="Invia">
          </td>
        </tr>
        </form>

<br>
<br>

</html>

This is my query.php file:

<?php
require 'connection.php';
// Inizio selezione

$usedatabase = "use " . $dbname;
if (isset($_POST['xxx'])) {
   $queryfinale = "select * from sergiodellera.mskselez where sesso='" . $_POST['xxx'] . "'" ;

}

//$final1 = mysql_query($usedatabase) or die(mysql_error());
//$final2 = mysql_query($queryfinale) or die(mysql_error());


//$query = mysql_query($queryfinale);
//$row = mysql_fetch_row($query);
//$final2 = $row[5];

echo $queryfinale;


?>

and this is my js file:

function myFunction() {
    var sex = document.forms["sexform"];
    var sez = document.forms["sezform"];
    var cla = document.forms["claform"];
    var txt = "";
    var txtsex = "";
    var txtsez = "";
    var txtcla = "";
    var isex;
    var isez;
    var icla;
    //FOR SEX
    for (isex = 0; isex < sex.length; isex++) {
        if (sex[isex].checked) {
            txtsex = txtsex + sex[isex].value;
        }
    }

    //FOR SEZ
     for (isez = 0; isez < sez.length; isez++) {
        if (sez[isez].checked) {
            txtsez = txtsez + sez[isez].value;
        }
    }
    //FOR CLA
     for (icla = 0; icla < cla.length; icla++) {
        if (cla[icla].checked) {
            txtcla = txtcla + cla[icla].value;
        }
    }
    txtsex = txtsex;
    txtsez = txtsez + ";";
    txtcla = txtcla + ";";
    txt = txtsex + txtsez + txtcla;
    for (sexfor = 0; sexfor < txtsex.length; sexfor++) {
        if (txtsex.length = 22){
            var asex = txtsex;
            var bsex = asex.substring(0, 1);
            var csex = asex.substring(7, 8);
            var dsex = asex.substring(14, 15);

        }
        if (txtsex.length = 15){
            var asex = txtsex;
            var bsex = asex.substring(0, 1);
            var csex = asex.substring(7, 8);

        }
        if (txtsex.length = 8){
            var asex = txtsex;
            var bsex = asex.substring(0, 1);
        }
break;
    }
    sexcontainer = bsex + csex + dsex;
    document.getElementById("outputfield").value = sexcontainer;
 //myFunction()   
}

function selectValues(){
    document.getElementById('xxx').value = sexcontainer;

    return true;
}

function query() { window.open("query.php");
}

I'm expecting that if i check for example male and female checkboxes i'll have a string like "MF". So, through a php variable i'm gonna have select * from tablename where sex=$varsex where varsex is MF

zero323
  • 322,348
  • 103
  • 959
  • 935
  • First I'd like to welcome you to SO here we help people who have problems with their code. In the question you posted you clearly have a problem with your code. In order to help you, you need to post it. What you also need to post is what you expect the code to do, what the error is you are getting. Go to this page to learn about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) – BRoebie Dec 14 '15 at 12:57
  • i've entered my code in the description of the problem – Sergio Dell'Era Dec 14 '15 at 14:40
  • This is way to much code as the how to ask page says keep it as little as possible. In this code we can't find the problem – BRoebie Dec 14 '15 at 14:49
  • Not much time tonight but let me know what you get stuck with. – Steve 5 mins ag0 – Steve Dec 14 '15 at 22:01
  • I don't know how to "post" a value to a php variable. It looks simple but it isn't. Is there a way to give a php variable the value of a button? I'm using your way of construction now because it's much cleaner and easier to understand – Sergio Dell'Era Dec 14 '15 at 22:08
  • When you submit your form to its `action="query.php"` by clicking your button your mysqli script is in there and you say `$all_sexes = $_POST['all_sexes'];` and use `$all_sexes` in your query - but at that stage you should clean the `$_POST['all_sexes']` to prevent it from being used in any inject attacks on your database. – Steve Dec 15 '15 at 00:29
  • Added some bits which might help with getting the results back from your form. You should be able to do without most of your JavaScript as long as you make sure that all your elements have a name as in `name="a_name"` which is what tells php there is a `$_POST` value to be picked up. $_POST is somewhat more secure than `$_GET` though it is not secure without cleaning up what you receive. Look ad "Prepared Statements" - your variables would be well suited to using that method to protect your database, and ensure that you are usinf mysqli rather than the old mysql which is prone to attack. – Steve Dec 15 '15 at 15:37
  • And a couple more bits added for getting your data into a string - which I think was what you were trying to achieve. `$abc_cnt++;` when it starts from 'A' increments as all letters - like at the top of an Excel sheet A-Z then AA, AB etc. Your `$_POST` vars are all letters for that section. – Steve Dec 16 '15 at 20:52
  • If you log on again here Sergio, would you consider accepting the below answer? It appears to have been very useful, but you have not voted on it or accepted it. To accept an answer, click on the tick mark to its left, to indicate that it was helpful. This rewards the answerer and encourages them to help people again. – halfer Feb 13 '16 at 13:20
  • @halfer Thanks for the edit - I was considering dropping the whole paragraph but felt it needed a health warning. I wonder why - apart from the HTML why the question got so many downvotes though. Getting variables by a letter name is something I once struggled with, as PHP won't accept purely numerical variable names and I had a similar script with dozens of single character textboxes which I needed to get the values from and couldn't figure out how to loop through them easily. Thanks for your support. – Steve Feb 13 '16 at 15:22
  • @Steve, no worries. In relation to the edit, some meta-commentary is OK, but I think there is a community view that giving voting advice (e.g. people requesting upvotes for their question) goes against the spirit of Stack Overflow. I thus generally discourage any voting/closing advice - and removing it makes posts more succinct anyway. In relation to the question, I'm afraid it deserved its downvotes IMO - see the edit history. The original had no code and no paragraphs, and then it was vandalised by the OP and had to be restored. It's OK now though. – halfer Feb 13 '16 at 21:31
  • 1
    @halfer Ahh I see Thanks. Your comment is very much in the spirit of this thread and much appreciated http://meta.stackoverflow.com/questions/258085/what-can-we-do-to-promote-reward-users-that-take-the-time-to-mentor-newbies-to-s/315361?noredirect=1#comment298432_315361 I felt a little nervous answering a question with many downvotes so was hoping to draw focus to the intent of the answer and didn't want to lose rep to the detail as there was still a lot of code that needed fixing in the HTML part which I never got round to. Agree asking for upvotes is bad form though! – Steve Feb 13 '16 at 22:02

1 Answers1

1

(This was a basic work in progress which has only a limited amount of functionality which I will attempt to improve if I have the time - it may still have technical faults - it is only intended to give an indication of what I think is needed - you will need to sort the results.)


The hidden input will be picked up by your php as $_POST['all_sexes'] and you could do something similar for other items. The difficult bit might be to edit the result on an "unclick" or change of mind.

You could use an onKeyPress event for the textboxes in a similar way. I would suggest putting it all in one form as it is all being submitted together.

This is the JavaScript:

 <script language="javascript">
 var all_sexes;
 var sex;

 function make_sex(sex){
 var sexes = document.getElementById('all_sexes').value
 if(sex == "Maschio"){sex = 'M';}
 if(sex == "Femmina"){sex = 'F';}
 if(sex == "Azienda"){sex = 'G';}
 if( sexes.indexOf(sex) >-1){ sex = '';} // working on what to do if unchecked and checked here
 all_sexes = document.getElementById('all_sexes').value + sex;

 document.getElementById('all_sexes').value = all_sexes;
 document.getElementById('outputfield').value = all_sexes;
 }
 </script>

And call the function in your checkbox with an onClick event passing it the value of the checkbox.

     Sesso
     <input type="checkbox" name="sex" value="Maschio" onclick="make_sex(this.value)"> M
     <input type="checkbox" name="sex" value="Femmina" onclick="make_sex(this.value)"> F
     <input type="checkbox" name="sex" value="Azienda" onclick="make_sex(this.value)"> G
     <input type="hidden" name="all_sexes" id="all_sexes" value="">

The html debugger is not happy with some text outside of spans but I am not here to look at that right now.

And, whatever you do do not put any POST variable content anywhere near your database without sanitizing it - see comments at the bottom of this page php registration form complication

Not sure if you actually need to display the click result on the page - if you don't and just want the submitted values this would be a much better approach - borrowed from PHP how to loop through a post array the accepted answer

 foreach( $_POST as $stuff ) {
    if( is_array( $stuff ) ) {
        foreach( $stuff as $thing ) {
           echo $thing . "<br />"; 
        } 
    } else { 
     echo $stuff ."<br />"; 
    }
  }

This is your html adapted to give you a quick demonstration of what it does - your php script shown here at the bottom would be on your query.php

There are a number of html errors where text is outside of the table elements which the debugger complains about - there are too many instances to fix here and perhaps you should be looking at a different structure rather than using tables for your framework as opposed to divs.

    <!DOCTYPE html>
    <html>
    <form name="code" method="post" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]);?>">
    <table border="0">
    <!-- ROW1 -->
    <tr>
    Da codice 
    <input type="text" name="dacode">
      a codice 
    <input type="text" name="acode">
    </tr>
    <!-- ROW2 -->   
    <br />          
    Sesso
    </tr>
    <tr>
    <input type="checkbox" name="Maschio" id="Maschio" value="Maschio" > M
    <input type="checkbox" name="Femmina" id="Femmina" value="Femmina" > F
    <input type="checkbox" name="Azienda" id="Azienda" value="Azienda" > G
    <!-- ROW3 -->
    <br>
    Da data nascita
    <input type="date" name="dadata" min="1980-01-01">
    a data nascita
    <input type="date" name="adata" min="1980-01-01">
    <!-- ROW4 -->
    <br>
    Sezioni
    <input type="checkbox" name="A" value="A"> A
    <input type="checkbox" name="B" value="B"> B
    <input type="checkbox" name="C" value="C"> C
    <input type="checkbox" name="D" value="D"> D
    <input type="checkbox" name="E" value="E"> E
    <input type="checkbox" name="F" value="F"> F
    <input type="checkbox" name="G" value="G"> G
    <input type="checkbox" name="H" value="H"> H
    <input type="checkbox" name="I" value="I"> I
    <input type="checkbox" name="J" value="J"> J
    <input type="checkbox" name="K" value="K"> K
    <input type="checkbox" name="L" value="L"> L
    <input type="checkbox" name="M" value="M"> M
    <input type="checkbox" name="N" value="N"> N
    <input type="checkbox" name="O" value="O"> O
    <input type="checkbox" name="P" value="P"> P
    <input type="checkbox" name="Q" value="Q"> Q
    <input type="checkbox" name="R" value="R"> R
    <input type="checkbox" name="S" value="S"> S
    <input type="checkbox" name="T" value="T"> T
    <input type="checkbox" name="U" value="U"> U
    <input type="checkbox" name="V" value="V"> V
    <input type="checkbox" name="W" value="W"> W
    <input type="checkbox" name="X" value="X"> X
    <input type="checkbox" name="Y" value="Y"> Y
    <input type="checkbox" name="Z" value="Z"> Z
    <br>
    <input type="checkbox" name="Ai" value="Ai"> Ai
    <input type="checkbox" name="Am" value="Am"> Am
    <input type="checkbox" name="Ae" value="Ae"> Ae
    <input type="checkbox" name="Bi" value="Bi"> Bi
    <input type="checkbox" name="Be" value="Be"> Be
    <input type="checkbox" name="sez" value="Bm"> Bm
    <input type="hidden" id="all_Bn" value="">
    <!-- ROW5 -->
    <br>
    Sezioni
    <input type="checkbox" name="Chk1" value="1"> 1
    <input type="checkbox" name="Chk2" value="2"> 2
    <input type="checkbox" name="Chk3" value="3"> 3
    <input type="checkbox" name="Chk4" value="4"> 4
    <input type="checkbox" name="Chk5" value="5"> 5
    </form>
    <br>
    <br>
     RESULT STRING
     <textarea type="text"  name="outputfield" id="outputfield"> </textarea>
     <input type="submit" name="submit" value="Invia">
                </td>
      </tr>
      </form>
      <br>
      <br>
      <?php
     foreach( $_POST as $stuff ) {
          if( is_array( $stuff ) ) {
              foreach( $stuff as $thing ) {
                echo $thing . "<br />"; 
             } 
          } else { 
            echo $stuff ."<br />"; 
          }
     }
     ?>
     </html>

A couple of other borrowed and slighty modified ideas which might help with handling the data sent by your form from:mysql_escape_string whole post array?

This one will just display what you set and its name and value:

    foreach(array_keys($_POST) as $key){ echo htmlspecialchars($key) . " " . htmlspecialchars($_POST[$key]) . "<br />";}

And this one is supposed to escape it (you need to be logged in to your sql session):

    foreach(array_keys($_POST) as $key){ $_POST[$key] = mysqli_real_escape_string($_POST[$key]); echo htmlspecialchars($key) . " " . htmlspecialchars($_POST[$key]);}

To collect the results from the A to Z checkboxes into a string where they have been checked this might work and has the advantage that you are not putting anything from the submitted value into your string.

     $abc = '';
     $abc_cnt = 'A';
     while( $abc_cnt1 < 26 ){
          if(isset($_POST[$abc_cnt])){
          $abc = $abc . $abc_cnt;
          }
     $abc_cnt++;
     $abc_cnt1++;
     }
     echo $abc;  // your result string for Sezzioni

The same applies to your other variables that you want to put into a string - for example if all the "Sesso" checkboxes are all clicked you will get "MFG" or you might have M and G or F and G.

     if (isset($_POST['Maschio'])) $sesso = $sesso . 'M';
     if (isset($_POST['Femmina'])) $sesso = $sesso . 'F';
     if (isset($_POST['Azienda'])) $sesso = $sesso . 'G';
Community
  • 1
  • 1
Steve
  • 808
  • 1
  • 9
  • 14