Sort by - Drop down menu

Discussion in 'PHP' started by software4, Oct 27, 2009.

  1. #1
    I am trying to get it so the candidates are sorted by join_candidate which is the (candidate name). I have tried in two different places and can not seem to get it to work. Any ideas?

    Line - 90-91
    mysql_select_db($database, $db_conn);
    $query_Recordset_join = "SELECT * FROM join2 ORDER BY join_candidate ASC";


    Line 240-241
    ORDER BY
    (join2.join_candidate ASC)";


    <?php require_once('Connections/config.php'); ?>
    <?php require_once('includes/system_values.php'); ?>
    <?php
    session_start();
    $MM_authorizedUsers = "";
    $MM_donotCheckaccess = "true";
    
    // *** Restrict Access To Page: Grant or deny access to this page
    function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
      // For security, start by assuming the visitor is NOT authorized. 
      $isValid = False; 
    
      // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
      // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
      if (!empty($UserName)) { 
        // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
        // Parse the strings into arrays. 
        $arrUsers = Explode(",", $strUsers); 
        $arrGroups = Explode(",", $strGroups); 
        if (in_array($UserName, $arrUsers)) { 
          $isValid = true; 
        } 
        // Or, you may restrict access to only certain users based on their username. 
        if (in_array($UserGroup, $arrGroups)) { 
          $isValid = true; 
        } 
        if (($strUsers == "") && true) { 
          $isValid = true; 
        } 
      } 
      return $isValid; 
    }
    //
    //Set logout function:
    $logoutAction = '?cmd=logout';
                if($_GET['cmd'] == 'logout')
                   {
                         $_SESSION['MM_Username'] == NULL;
                        $_SESSION['MM_UserGroup'] == NULL;
                       unset($_SESSION['MM_Username']);
                       unset($_SESSION['MM_UserGroup']);
                      session_destroy();
                   }
    			   
    
    $MM_restrictGoTo = "index.php";
    if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
      $MM_qsChar = "?";
      $MM_referrer = $_SERVER['PHP_SELF'];
      if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
      if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) 
      $MM_referrer .= "?" . $QUERY_STRING;
      $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
      header("Location: ". $MM_restrictGoTo); 
      exit;
    }
    ?>
    <?php
    function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
    {
      $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;
    
      switch ($theType) {
        case "text":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;    
        case "long":
        case "int":
          $theValue = ($theValue != "") ? intval($theValue) : "NULL";
          break;
        case "double":
          $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
          break;
        case "date":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;
        case "defined":
          $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
          break;
      }
      return $theValue;
    }
    
    $editFormAction = $_SERVER['PHP_SELF'];
    if (isset($_SERVER['QUERY_STRING'])) {
      $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
    }
    
    
    mysql_select_db($database, $db_conn);
    $query_Recordset_join = "SELECT * FROM join2 ";
    $Recordset_join = mysql_query($query_Recordset_join, $db_conn) or die(mysql_error());
    $row_Recordset_join = mysql_fetch_assoc($Recordset_join);
    $totalRows_Recordset_join = mysql_num_rows($Recordset_join);
    
    mysql_select_db($database, $db_conn);
    $query_Recordset1 = "SELECT * FROM voting_result";
    $Recordset1 = mysql_query($query_Recordset1, $db_conn) or die(mysql_error());
    $row_Recordset1 = mysql_fetch_assoc($Recordset1);
    $totalRows_Recordset1 = mysql_num_rows($Recordset1);
    
    mysql_select_db($database, $db_conn);
    $query_Recordset2 = "SELECT * FROM poll";
    $Recordset2 = mysql_query($query_Recordset2, $db_conn) or die(mysql_error());
    $row_Recordset2 = mysql_fetch_assoc($Recordset2);
    $totalRows_Recordset2 = mysql_num_rows($Recordset2);
    
    mysql_select_db($database, $db_conn);
    
    ?>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>Voting 4 Students</title>
    <link href="style.css" rel="stylesheet" type="text/css">
    <style type="text/css">
    <!--
    .style4 {font-weight: bold}
    .style5 {
        color: #000000;
        font-weight: bold;
    }
    #results {
    	float:left;
    	width: 300px;
    	}
    -->
    </style>
    <script type="text/javascript" src="javascript/biography.js"></script>
    </head>
    <table width="744" border="0" align="center" cellpadding="0" cellspacing="0">
      <tr>
        <td colspan="3"><div align="center"><table width="750" border="0" cellspacing="0" cellpadding="0">
            <tr>
              <td height="90" background="images/header_back.jpg"><div align="center" class="title"><? echo "$school" ; ?> </div></td>
            </tr>
          </table></div></td>
      </tr>
      <tr>
        <td width="14" height="25">&nbsp;</td>
        <td background="images/menu_back_tmp.png" bgcolor="#FFFFFF"><table width="727" border="0" cellpadding="0" cellspacing="0">
          <tr>
           
            <td height="24" align="left" valign="middle" background="images/menu_back.png">&nbsp;</td>
            </tr>
        </table></td>
        <td width="15">&nbsp;</td>
      </tr>
      <tr>
        <td width="14">&nbsp;</td>
        <td width="727" height="400" align="center" valign="top" bgcolor="#FFFFFF">
          <div align="center">
    
      
                <table width="699" border="0" align="center" cellpadding="0" cellspacing="5">
              <tr>
                <td valign="top"><div align="left">
                  <p align="right">&nbsp;</p>
                  <p align="center" class="style1">Vote for Each Candidate </p>
                  <table width="700" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                      <td width="150">&nbsp;</td>
                      <td width="454">
                      
    <?php 
    $currentDate = date('Y-m-d');
    //find a unique identifier for the user -- his IP address 
    $db_connr = (!empty($_SERVER['HTTP_CLIENT_IP'])) ? $_SERVER['HTTP_CLIENT_IP'] : $_SERVER['REMOTE_ADDR'];
    $db_connr = (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $db_connr;
    $db_connr = (!empty($_SERVER['HTTP_X_FORWARDED'])) ? $_SERVER['HTTP_X_FORWARDED'] : $db_connr;
    $db_connr = (!empty($_SERVER['HTTP_FORWARDED_FOR'])) ? $_SERVER['HTTP_FORWARDED_FOR'] : $db_connr;
    $db_connr = (!empty($_SERVER['HTTP_FORWARDED'])) ? $_SERVER['HTTP_FORWARDED'] : $db_connr;
    
    //$MM_Username = '1324n2'; 
    
    //print_r($_POST['position']); 
    
    //Check to see if the submit button has been hit 
    if($_POST['submit']) 
        { 
            //escape our strings to protect from sql injection attacks --  
            //You could add more checks here 
            $election = mysql_real_escape_string($_POST['election']); 
            $position = $_POST['position']; 
         
         
            //check to see if the user has already voted 
            $checkDb = "SELECT * FROM `voting_result` WHERE `student_id`='$MM_Username' AND `election`='$election'"; 
                $resultDb = mysql_query($checkDb); 
                if(mysql_affected_rows() < 1) 
                    { 
    					$date = date('Y-m-d H:i:s');
                        foreach($position as $key => $value) 
                            { 
                                $position = mysql_real_escape_string($value); 
                                $id = mysql_real_escape_string($_POST[$value]); 
                                $position = str_replace('_',' ',$position); 
                                 
                                //if user hasn't voted, insert the query, and echo him a thank you. 
                                mysql_query("INSERT INTO `voting_result`(ip,election,position,id,time_stamp,student_id)  
                                            VALUES 
                                            ('$db_connr','$election','$position','$id','$date','$MM_Username')"); 
                                 
                            } 
                        $message = '<span class="SubHeaderMain"><center>Thanks for voting!</center></span><br/>'; 
                    } 
                    //if the user has voted, tell him that. 
                else $message = '<span class="SubHeaderMain"><center>You have already voted!<br/>You cannot vote again.</center></span>'; 
            mysql_free_result($resultDb); 
        } 
    
    
             
    //Run our general page data 
    if($_POST['choosePoll']) 
        { 
    		$title = mysql_real_escape_string(trim(strip_tags($_POST['title'])));
    		
    		$sql= "SELECT `poll_title` FROM `poll` WHERE `poll_id`='$title'";
    			$result= mysql_query($sql);
    				$r = mysql_fetch_row($result);
    					$event = $r[0];
    			$sql = NULL;
    			$result = NULL;
    			$r = NULL;
    			
           // $query = "SELECT * FROM `join2` WHERE `join_event_id`='$title'"; 
    	   $query = "SELECT join2.*, poll.poll_title, poll.bio FROM join2  
                LEFT JOIN 
                    poll 
                ON 
                    (join2.join_event_id = poll.poll_id) 
                WHERE  
                    ('$currentDate' BETWEEN poll.poll_start AND poll.poll_end)
    			AND
    				join2.join_event_id = '$title'";  
    
    			//echo $query;
                $result = mysql_query($query); 
                    if(mysql_affected_rows() > 0) 
                        { 
                           while($row = mysql_fetch_array($result)) 
                                    { 
                                        $join_id = $row['join_id'];  
             
                                        //make sure form name's don't have whitespace 
                                        $join_event_id = $row['join_event_id'];  
                                        $join_position = str_replace(' ','_',$row['join_position']);  
                                        $join_candidate = $row['join_candidate'];
    									$poll_title = $row['poll_title'];
           
    									$showBio[] = $row['bio'];
                                            //create a storage array  
                                        $storage["$join_event_id"]["$poll_title"]["$join_position"]["$join_candidate"] = $join_id;   
                                    }
    							
    							$onchange = (in_array(1,$showBio)) ? 1 : 0 ;
    							//echo $onchange;
    							$divIDHolder = 0;
                                //cycle through our array to build our forms.    
    							mysql_free_result($result);
                                foreach($storage as $key => $value) 
                                    { 
                                        echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post">' 
                                            .'<input type="hidden" name="election" value="'.$key.'"/>'; 
    										
    										foreach($value as $key2 => $value2)
    											{
    											echo '<span class=style2>' . '<center>' .  $key2 . '</center>' . '</span>' . '<br/>'; 
                     
                     
                                            foreach($value2 as $key3 => $value3) 
                                                { 
    												$divID = 'result' . $divIDHolder;
    												$divIDHolder++;
                                                    echo '<br/>' . '<hr>' . '<br/>' . '<span class=SubHeaderMain>'. str_replace('_',' ',$key3) . ':   ' . '</span>' . "\n"  
    														.'<input type="hidden" name="position[]" value="'.$key3.'"/>' . "\n" 
    														.'<select name="'.$key3.'" id="election"';
    												echo ($onchange === 1) ? ' onchange="sendBio(this.options[this.selectedIndex].value,\''. $divID .'\');">' : '>';
    												echo "\n" .'<option value="0">--Select a Candidate--</option>' . "\n";
                                             
                                     
                                                    if(is_array($value3)) 
                                                        { 
                                                            foreach($value3 as $key4 => $value4) 
                                                                { 
                                                                    echo '<option value="'.$value4.'">'.$key4.'</option>'; 
                                                                } 
                                                        } 
                                                    else 
                                                        { 
                                                            echo '<option value="NULL">Not Set</option>'; 
                                                        }                                 
                                         
                                                    echo '</select>' . '<div id="' . $divID .'" style="padding:5px;">&nbsp;</div>' . "\n" //div resides after the select box ends.
                                                       ; 
                                                } 
                         
                                echo '<br/>' . '<hr>' . '<br/>' . '<input type="submit" name="submit" value="  SUBMIT  "/>' 
                                    .'</form>'; 
    									}
                                    } 
                            
    						echo (isset($message)) ? $message: '';
                             
                        } 
                    else{ echo 'You have encountered an error, please alert Adminstrator!';} 
           
        } 
    else{ 
         
    //Set the query to build forms  
    $query = "SELECT join2.*, poll.poll_title, poll.bio FROM join2  
                LEFT JOIN 
                    poll 
                ON 
                    (join2.join_event_id = poll.poll_id) 
                WHERE  
                    ('$currentDate' BETWEEN poll.poll_start AND poll.poll_end)";  
    
    //see if the user has already voted 
    //This is different than the above, that is 
    //only called when the user submit's data 
    $searchQuery = "SELECT * FROM `voting_result` WHERE `student_id`='$MM_Username'"; 
        $search = mysql_query($searchQuery); 
         
        //set variable declaring that user hasn't 
        //voted, this can be accessed by echo. 
        $userVotingStatus = 'You have not Voted!'; 
         
        //if we find the user already in the database, we  
        //will sort his data.  We will only show data 
        //if he has input similar data. 
        if($ar = mysql_affected_rows() > 0) 
            { 
                 
     //re-declare variable if user found in voting table  
                //still access using echo;  
                $userVotingStatus = 'You have already Voted!';  
                  
                  
                $election = array();  
                while($searchResult = mysql_fetch_array($search))  
                    {  
                        //put data in an array.  
                        $election[] = $searchResult['election'];  
                          
                    }  
                      
                //Un-comment next line to see what the election array looks like;  
                //print_r($election);  
                  
                //extract all duplicate keys inside the array $election;  
                $election = array_unique($election);  
                  
                //Un-comment the next two lines to see what the election array has changed to;  
                //echo '<br/><br/>';  
                //print_r($election);  
                 
                  //resort the election array to put an array inside the mysql_query string;  
                                        $c = count($election);  
                                        $i = 0;  
                                        foreach($election as $value)  
                                            {                                          
                                                $queryCommaSeperatedList .= ($i == ($c - 1)) ? "'$value'" : "'$value',";  
                                                $i++;  
                                            }  
                  
                //append the $query, add a where clause  
                $query .= "AND (`join2`.`join_event_id` NOT IN ($queryCommaSeperatedList))";  
                $appendActivePoll = "AND `poll`.`poll_id` NOT IN ($queryCommaSeperatedList)"; 
                      
            }   
            mysql_free_result($search); 
                //make a query that will select active polls 
                $activePoll = "SELECT `poll_id`, `poll_title` FROM `poll` 
                                    WHERE  
                                        ('$currentDate' BETWEEN `poll_start` AND `poll_end`) $appendActivePoll"; 
         
                $pollResult = mysql_query($activePoll); 
                $af = mysql_affected_rows(); //echo $af .'<br/><br/>' . $activePoll;
                    if($af > 1) 
                        { 
                            while($pollRow = mysql_fetch_row($pollResult)) 
                                { 
                                    $pollStorage[$pollRow[1]] = $pollRow[0]; 
                                } 
                            if(is_array($pollStorage)) 
                                { 
                                    echo '<center>' . '<form action="" method="post">' 
                                        .'<select name="title">'; 
                                    foreach($pollStorage as $key => $value) 
                                        { 
                                            echo '<option value="'.$value.'">'.$key.'</option>'; 
                                        } 
                                    echo '</select>'  . '&nbsp;' . '&nbsp;'
                                        .'<input type="submit" name="choosePoll" value="Submit"/>' . '</center>'
                                        .'</form>'; 
                                } 
                            else{ echo 'There was an error with our forms, please alert an administrator!';} 
                        mysql_free_result($pollResult); 
    						echo (isset($message)) ? $message : '';
                        } 
                    elseif($af == 1) 
                        { 
                         
                      
                        //echo $userVotingStatus; 
                        //At this time we have ended the Voting results 
                        //And we have built a query to call the voting 
                        //Forms. 
    					//echo $query;
                        //call the query 
                        $result = mysql_query($query); 
    
                        //if we have data to pull, populate it. 
                        if(mysql_affected_rows() > 0) 
                            { 
         
                                while($row = mysql_fetch_array($result)) 
                                    { 
                                        $join_id = $row['join_id'];  
             
                                        //make sure form name's don't have whitespace 
                                        $join_event_id = $row['join_event_id'];  
                                        $join_position = str_replace(' ','_',$row['join_position']);  
                                        $join_candidate = $row['join_candidate'];
    									$poll_title = $row['poll_title'];
           
    									$showBio[] = $row['bio'];
                                            //create a storage array  
                                        $storage["$join_event_id"]["$poll_title"]["$join_position"]["$join_candidate"] = $join_id;   
                                    }
    							
    							$onchange = (in_array(1,$showBio)) ? 1 : 0 ;
    							//echo $onchange;
    							$divIDHolder = 0;
                                //cycle through our array to build our forms.     
                                foreach($storage as $key => $value) 
                                    { 
                                        echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post">' 
                                            .'<input type="hidden" name="election" value="'.$key.'"/>'; 
    										
    										foreach($value as $key2 => $value2)
    											{
    											echo '<span class=style2>' . '<center>' .  $key2 . '</center>' . '</span>' . '<br/>'; 
                     
                     
                                            foreach($value2 as $key3 => $value3) 
                                                { 
    												$divID = 'result' . $divIDHolder;
    												$divIDHolder++;
                                                    echo '<br/>' . '<hr>' . '<br/>' . '<span class=SubHeaderMain>'. str_replace('_',' ',$key3) . ':   ' . '</span>' . "\n"  
    														.'<input type="hidden" name="position[]" value="'.$key3.'"/>' . "\n" 
    														.'<select name="'.$key3.'" id="election"';
    												echo ($onchange === 1) ? ' onchange="sendBio(this.options[this.selectedIndex].value,\''. $divID .'\');">' : '>';
    												echo "\n" .'<option value="0">--Select a Candidate--</option>' . "\n";
                                             
                                     
                                                    if(is_array($value3)) 
                                                        { 
                                                            foreach($value3 as $key4 => $value4) 
                                                                { 
                                                                    echo '<option value="'.$value4.'">'.$key4.'</option>'; 
                                                                } 
                                                        } 
                                                    else 
                                                        { 
                                                            echo '<option value="NULL">Not Set</option>'; 
                                                        }                                 
                                         
                                                    echo '</select>' . '<div id="' . $divID .'" style="padding:5px;">&nbsp;</div>' . "\n" //div resides after the select box ends.
                                                       ; 
                                                } 
                         
                                echo '<br/>' . '<hr>' . '<br/>' . '<input type="submit" name="submit" value="  SUBMIT  "/>' 
                                    .'</form>'; 
    									}
                                    } 
                            } 
    						echo (isset($message)) ? $message: '';
                            mysql_free_result($result); 
                        } 
                    else{ echo (isset($message)) ? $message : '<span class="SubHeaderMain"><br/><center>You have already voted in all available elections!</center></span>'; }  
                 
             
        } 
    ?></td>
                      <td width="150">&nbsp;</td>
                    </tr>
                  </table>
                  <p align="center" class="style1">&nbsp;</p>			
                  <p align="center" class="style1">&nbsp;</p>
                  <p align="center" class="style1">&nbsp;</p>
                  <p align="center">&nbsp;</p>
                    <p align="center"><br>
                    </p>
                    <p align="center">&nbsp;</p>
                    <p align="center"><a href="<?php echo $logoutAction ?>">Log out</a></p>
                </div></td>
              </tr>
            </table>
            <span class="main">Admin: <a href="admin_login.php">Login</a></span><br>
        </div>      </td>
        <td width="15">&nbsp;</td>
      </tr>
      <tr>
        <td colspan="3"><table width="750" border="0" cellspacing="0" cellpadding="0">
          <tr>
            <td width="750" height="69" background="images/footer_back_tmp.png"><div align="center" class="footer"><span class="style4">Copyright &copy;2009</span> <a href="http://www.software4schools.com" target="_blank">Software 4 Schools</a> </div></td>
          </tr>
        </table></td>
      </tr>
    </table>
    </body>
    </html>
    <?php
    mysql_free_result($Recordset_join);
    
    mysql_free_result($Recordset1);
    
    mysql_free_result($Recordset2);
    ?>
    PHP:
     
    software4, Oct 27, 2009 IP