Visualizzazione dei risultati da 1 a 5 su 5
  1. #1

    Cookie per Sondaggio PHP e MYSQL

    Ciao a tutti, ho creato uno script PHP per un sondaggio.
    Di seguito il codice dei due files che lo compongono:

    index.php
    Codice PHP:
      <?php
      
    include ('Poll.php');  $poll = new Poll();  $voted 0;  $pollData $poll->getPoll();  if(isset($_POST['vote'])){    $pollVoteData = array(      'sondaggioid' => $_POST['sondaggioid'],      'pollOptions' => $_POST['options']    );        $isVoted $poll->updateVote($pollVoteData);    if($isVoted){      setcookie($_POST['sondaggioid'], 1time()+60*60*24*365);      $voted 1;    } else {      $voted 2;    }  }

      
    ?>        <?php if(!empty($voted) && $voted === 1) {        echo '<div class="alert alert-success">Hai votato con successo.</div>';           }      else if(!empty($voted)  && $voted === 2) {        echo '<div class="alert alert-danger">Your had already voted.</div>';      }      ?>      <form action="" method="post" name="pollForm">      <?php foreach($pollData as $poll){        $pollOptions explode("||||"$poll['options']);?>                     <?php echo $poll['question']?>
                    <?php for( $i 0$i count($pollOptions); $i++ ) { ?>
                          <label>                        <input type="radio" name="options" value="<?php echo $i?>">                        <?php echo $pollOptions[$i]?>                      </label>                                 <?php }?>
                  <input type="hidden" name="sondaggioid" value="<?php echo $poll['sondaggioid']; ?>"/>              <button type="submit" class="btn btn-primary btn-sm" id="vote" name="vote">              Vote</button>        <?php }?>      </form>
    Poll.php
    Codice PHP:
    <?phpclass Poll{private $host 'localhost';private $user 'root';private $password '';private $database 'sondaggio';private $pollTable 'poll';private $dbConnect false;public function __construct(){if(!$this->dbConnect){$conn = new mysqli($this->host$this->user$this->password$this->database);if($conn->connect_error){die("Error failed to connect to MySQL: " $conn->connect_error);}else{$this->dbConnect $conn;}}}private function getData($sqlQuery) {$result mysqli_query($this->dbConnect$sqlQuery);if(!$result){die('Error in query: 'mysqli_error());}$data= array();while ($row mysqli_fetch_array($resultMYSQLI_ASSOC)) {$data[]=$row;}return $data;}public function getPoll(){$sqlQuery 'SELECT sondaggioid, question, options, votes, voters FROM '.$this->pollTable;return $this->getData($sqlQuery);}public function getVotes($sondaggioid){$sqlQuery 'SELECT votes, voters FROM '.$this->pollTable.' where sondaggioid = '.$sondaggioid;$result mysqli_query($this->dbConnect$sqlQuery);return mysqli_fetch_array($resultMYSQLI_ASSOC);}public function updateVote($pollVoteData) {if(!isset($pollVoteData['sondaggioid']) || isset($_COOKIE[$pollVoteData['sondaggioid']])) {return false;}$pollVoteDetails $this->getVotes($pollVoteData['sondaggioid']);$votes explode("||||"$pollVoteDetails['votes']);$votes[$pollVoteData['pollOptions']] += 1;implode("||||",$votes);$pollVoteDetails['voters'] += 1;$sqlQuery "UPDATE ".$this->pollTable." set votes = '".implode("||||",$votes)."' , voters = '".$pollVoteDetails['voters']."' where sondaggioid = '".$pollVoteData['sondaggioid']."'";mysqli_query($this->dbConnect$sqlQuery);return true;}}?>
    Tutto funziona correttamente tranne il cookie che dovrebbe bloccare il secondo voto da parte dell'utente.
    E' come se il cookie non venisse nemmeno impostato sul browser dell'utente, non c'è traccia.
    Qualcuno sa dirmi cosa potrebbe essere?
    Io ho la necessità di consentire un solo voto all'utente, perciò al primo accesso alla pagina quando invia il voto viene salvato un cookie che non consentirà un altro voto.

    Grazie mille
    MF

  2. #2
    Moderatore di PHP L'avatar di Alhazred
    Registrato dal
    Oct 2003
    Messaggi
    12,450
    Un codice così mal formattato è difficile da leggere, prima di inviare i post contenenti del codice visualizza l'anteprima e se necessario riformattalo a mano.

    Comunque in questo caso intanto prova ad indicare anche il dominio nella funzione setcookie(), è facoltativo, ma meglio mettercelo.

  3. #3
    index.php
    codice:
      <?php
    
    
      include ('Poll.php');
      $poll = new Poll();
      $voted = 0;
      $pollData = $poll->getPoll();
      if(isset($_POST['vote'])){
        $pollVoteData = array(
          'sondaggioid' => $_POST['sondaggioid'],
          'pollOptions' => $_POST['options']
        );
        
        $isVoted = $poll->updateVote($pollVoteData);
        if($isVoted){
          setcookie($_POST['sondaggioid'], 1, time()+60*60*24*365);
          $voted = 1;
        } else {
          $voted = 2;
        }
      }
      ?>
    
    
      <div class="container">
        <div class="row">
          <?php if(!empty($voted) && $voted === 1) {
            echo '<div class="alert alert-success">Hai votato con successo.</div>';        
          }
          else if(!empty($voted)  && $voted === 2) {
            echo '<div class="alert alert-danger">Your had already voted.</div>';
          }
          ?>
          <form action="" method="post" name="pollForm">
          <?php foreach($pollData as $poll){
            $pollOptions = explode("||||", $poll['options']);?>
            <div class="col-md-3">
              <div class="panel panel-primary">
                <div class="panel-heading">
                  <h3 class="panel-title">
                   <?php echo $poll['question']?>
                  </h3>
                </div>
                <div class="panel-body">
                  <ul class="list-group">
                    <?php for( $i = 0; $i < count($pollOptions); $i++ ) { ?>
    
    
                      <li class="list-group-item">
                        <div class="radio">
                          <label>
                            <input type="radio" name="options" value="<?php echo $i; ?>">
                            <?php echo $pollOptions[$i]?>
                          </label>
                        </div>
                      </li>
                    <?php }?>
    
    
                  </ul>
                </div>
                <div class="panel-footer">
                  <input type="hidden" name="sondaggioid" value="<?php echo $poll['sondaggioid']; ?>"/>
                  <button type="submit" class="btn btn-primary btn-sm" id="vote" name="vote">
                  Vote</button>
                  </div>
                </div>
              </div>
            <?php }?>
          </form>
          </div>
        </div>
      </body>
      </html>

    Poll.php
    codice:
    <?php
    class Poll{
    private $host = 'localhost';
    private $user = 'root';
    private $password = '';
    private $database = 'sondaggio';
    private $pollTable = 'poll';
    private $dbConnect = false;
    public function __construct(){
    if(!$this->dbConnect){
    $conn = new mysqli($this->host, $this->user, $this->password, $this->database);
    if($conn->connect_error){
    die("Error failed to connect to MySQL: " . $conn->connect_error);
    }else{
    $this->dbConnect = $conn;
    }
    }
    }
    private function getData($sqlQuery) {
    $result = mysqli_query($this->dbConnect, $sqlQuery);
    if(!$result){
    die('Error in query: '. mysqli_error());
    }
    $data= array();
    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $data[]=$row;
    }
    return $data;
    }
    public function getPoll(){
    $sqlQuery = 'SELECT sondaggioid, question, options, votes, voters FROM '.$this->pollTable;
    return $this->getData($sqlQuery);
    }
    public function getVotes($sondaggioid){
    $sqlQuery = 'SELECT votes, voters FROM '.$this->pollTable.' where sondaggioid = '.$sondaggioid;
    $result = mysqli_query($this->dbConnect, $sqlQuery);
    return mysqli_fetch_array($result, MYSQLI_ASSOC);
    }
    public function updateVote($pollVoteData) {
    if(!isset($pollVoteData['sondaggioid']) || isset($_COOKIE[$pollVoteData['sondaggioid']])) {
    return false;
    }
    $pollVoteDetails = $this->getVotes($pollVoteData['sondaggioid']);
    $votes = explode("||||", $pollVoteDetails['votes']);
    $votes[$pollVoteData['pollOptions']] += 1;
    implode("||||",$votes);
    $pollVoteDetails['voters'] += 1;
    $sqlQuery = "UPDATE ".$this->pollTable." set votes = '".implode("||||",$votes)."' , voters = '".$pollVoteDetails['voters']."' where sondaggioid = '".$pollVoteData['sondaggioid']."'";
    mysqli_query($this->dbConnect, $sqlQuery);
    return true;
    }
    }
    ?>

  4. #4
    Ciao Alhazred hai ragione, scusami ma non ci ho fatto caso, e lo avevo anche sistemato prima di inviarlo!
    Ho inviato nuovamente il codice verificando che sia formattato correttamente.
    Grazie mille

  5. #5
    Moderatore di PHP L'avatar di Alhazred
    Registrato dal
    Oct 2003
    Messaggi
    12,450
    Però non hai seguito il consiglio di aggiungere il dominio tra i parametri della funzione setcookie(), provaci.

  6. #6
    Ho inserito il cookie con il sottodominio su dove ho messo questo script quindi:

    codice:
    setcookie($_POST['sondaggioid'], 1, time()+60*60*24*365,'/','.corporate.it',false);
    Ho provato a mettere nel codice PHP un var_dump($_COOKIE); e non mi da nessun cookie che sto impostando, è come se qualcosa me li cancellasse.

    Ho provato anche a specificare il dominio del cookie per estero (sono su un subdomain).

    Quote Originariamente inviata da Alhazred Visualizza il messaggio
    Però non hai seguito il consiglio di aggiungere il dominio tra i parametri della funzione setcookie(), provaci.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.