Poll script

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pritam79
Forum Commoner
Posts: 65
Joined: Wed Mar 26, 2008 9:28 am

Poll script

Post by pritam79 »

I am trying the poll script using MySql with PHP, this is what I have done so far.

This is the poll.htm file

Code: Select all

<html>
<head>
</head>
<body>
<div id="poll">
<h3>Do you like PHP and AJAX so far?</h3>
<form action="poll_vote.php" method="post">
Yes:
<input type="radio" name="vote" value="1">
<br>No:
<input type="radio" name="vote" value="0">
<input type="submit">
</form>
</div>
</body>
</html>
And this is the poll_vote.php-

Code: Select all

<?php
 
$vote = $_POST['vote'];  // $vote is 1 if YES is selected 
                          // and $vote is 0 if NO is selected
                          
$con=mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
  
mysql_select_db("poll");
 
$result=mysql_query("SELECT * FROM poll_result");
 
while($row = mysql_fetch_array($result))  
  {  
   if($vote == 1)
    {
     $row['Yes'] += 1;  // increment values in the database
    }
   if($vote == 0)
    {
     $row['No'] += 1;
    }
  }
mysql_query("UPDATE poll_result SET YES = '{$row['Yes']}', NO = '{$row['No']}'");
 
while($row = mysql_fetch_array($result))  
  {
   echo "<p>Total votes= ".($row['Yes'] + $row['No'])."</p>";
  
   echo "<p>Yes= ".$row['Yes']."</p>";
  
   echo "<p>No= ".$row['No']."</p>";
  }
 
?>
On selecting either Yes or No option from the html form, I am getting this error-

Code: Select all

Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `T_NUM_STRING' in C:\wamp\www\poll\poll_vote.php on line 27.
 
The database is not getting updated anyway, but is there anything wrong with the script? Also please suggest the simplest form of this same script using PHP MySQL. I would also like to know where I am going wrong with my current scripts. Thanks……
User avatar
turbolemon
Forum Commoner
Posts: 70
Joined: Tue Jul 14, 2009 6:45 am
Location: Preston, UK

Re: Poll script

Post by turbolemon »

Change

Code: Select all

mysql_query("UPDATE poll_result SET YES = '{$row['Yes']}', NO = '{$row['No']}'");
to maybe:

Code: Select all

mysql_query("UPDATE poll_result SET YES = '$row[Yes]', NO = '$row[No]'");
PHP evaluates variables within double-quoted strings, as well as special characters ("\n", "\t", etc.).
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: Poll script

Post by Darhazer »

Offtopic

This is a poll script I've wrote some time ago for my web site... It contains both admin and user part. If it's helpful for anyone, feel free to use it

Code: Select all

<?php
 
class Poll {
    
    public $question;
    public $id;
    public $answers = array();
    public $voted = false;
    public $votes = array();
 
    public function __construct($id, $data = false)
    {
        $this->id = $id > 0 ? $id : 0;
 
        if ( $this->id && is_object( $data ) == false )
        {
            $sql = 'SELECT * FROM itl_polls WHERE id = '.intval( $id );
            $data = DB::Instance()->query_first( $sql );
        }
 
        if ( is_object( $data ) )
        {
            $this->question = $data->question;
            $this->answers = $this->_loadAnswers();
            $this->votes = $this->_loadVotes();
            $this->voted = $this->_checkVote();         
        } else {
            $this->id = 0;
        }
    }
 
    private function _loadAnswers()
    {
        $sql = 'SELECT * FROM itl_answers WHERE poll_id='.$this->id;
        $res = DB::Instance()->query( $sql );
        $count = DB::Instance()->num_rows($res);
        
        $answers = array();
        for ($i = 0; $i < $count; $i++ )
        {
            $row = DB::Instance()->get_row($res);
            $answers[ $row->id ] = $row->answer;
        }
        return $answers;
    }
 
    private function _loadVotes()
    {
        $sql = 'SELECT answer_id, count(*) as count FROM itl_votes WHERE poll_id = '.$this->id.' GROUP BY answer_id';
        $res = DB::Instance()->query( $sql );
        $count = DB::Instance()->num_rows($res);
        
        $votes = array();
        for ($i = 0; $i < $count; $i++ )
        {
            $row = DB::Instance()->get_row($res);
            $votes[ $row->answer_id ] = $row->count;
        }
        return $votes;
    }
 
    private function _checkVote()
    {
        // check if user have voted for this poll
        // 1st: check via cookie
        if (is_array($_COOKIE['polls']) == false ) 
        {
            $_COOKIE['polls'] = array($_COOKIE['polls']);
        }
        if ( in_array( $this->id, $_COOKIE['polls'] ) )
        {
            $this->voted = true;
            return true;
        }
 
        // 2nd: check via member_id 
        if ( isset($_SESSION['user']) ) 
        {
            $id = $_SESSION['user']->getUserID();
            $sql = 'SELECT * FROM itl_votes WHERE user_id = '.$id.' AND answer_id IN ('.implode( ',', array_keys( $this->answers ) ).')';
            $res = DB::Instance()->query( $sql );
            
            if (DB::Instance()->num_rows($res) > 0)
            {
$this->voted = true;
                return true;
            }
        }
 
        return false;
    }
 
    public function Vote($answer_id, $member_id, $ip)
    {
        if ( $this->voted ) 
        {
            return false;
        }
 
        if ( in_array($answer_id, array_keys($this->answers) ) == false )
        {
            return false;
        }
 
        $date = date("Y-m-d");
        
        $sql = 'INSERT INTO itl_votes (answer_id, user_id, ip, date, poll_id) VALUES';
        $sql .= sprintf( ' (%d, %d, "%s", "%s", %d) ', $answer_id, $member_id, $ip, $date, $this->id );
        
        $res = DB::Instance()->query( $sql );
 
        setcookie("polls[]", $this->id, time() + (60*60*24*365) );
        $this->voted = true;
        return true;
    }
 
    public function Update($data)
    {
        // TODO: Transaction
        $DB = DB::Instance();
        if ($this->id)
        {
            $sql = sprintf('UPDATE itl_polls SET question = "%s" WHERE id = %d', $DB->escape_string( $data['question'] ), $this->id );
            $res = $DB->query( $sql );
 
            // asnwers to remove
            $deletedAnswers = array_diff( array_keys($this->answers), array_keys($data['answers'])  );
            $sql = 'DELETE FROM itl_answers WHERE id IN ('.implode(',', $deletedAnswers).')';
            $result = $DB->query( $sql );
        
            foreach ( $data['answers'] as $id => $answer )
            {
                if ($id > 0)
                {
                    $sql = sprintf('UPDATE itl_answers SET answer = "%s" WHERE id = %d', $DB->escape_string( $answer ), intval( $id ) );
                } else {
                    $sql = sprintf('INSERT INTO itl_answers(poll_id, answer) VALUES(%d, "%s")', intval($this->id), $DB->escape_string( $answer ) );
                }
                $result = $DB->query( $sql );
            }
            return true;
        }
        
        $sql = sprintf('INSERT INTO itl_polls(question) VALUES ("%s")', $DB->escape_string( $data['question'] ) );
        $result = $DB->query( $sql );
        $id = $DB->insert_id();
 
        foreach ( $data['answers'] as $a_id => $answer )
        {
            $sql = sprintf('INSERT INTO itl_answers(poll_id, answer) VALUES(%d, "%s")', $id, $DB->escape_string($answer) );
            $result = $DB->query( $sql );
        }
 
        return true;
    }
 
 
    public function Delete()
    {
        // TODO: Transaction
        $sql = 'DELETE FROM itl_votes WHERE answer_id IN ('.implode( ',', array_keys( $this->answers ) ).')';
        $result = DB::Instance()->query( $sql );
        
        $sql = 'DELETE FROM itl_answers WHERE poll_id = '.$this->id;
        $result = DB::Instance()->query( $sql );
 
        $sql = 'DELETE FROM itl_polls WHERE id = ' . $this->id;
        $result = DB::Instance()->query( $sql );
 
        return true;
    }
 
    static public function GetPolls()
    {
        $sql = 'SELECT * FROM itl_polls';
        $res = DB::Instance()->query( $sql );
        $count = DB::Instance()->num_rows($res);
 
        $polls = array();
        for ($i = 0; $i < $count; $i++)
        {
            $row = DB::Instance()->get_row($res);
            $polls[] = new Poll($row->id, $row);
        }
 
        return $polls;
    }
 
    static public function GetCurrentPoll()
    {
        $sql = 'SELECT * FROM itl_polls ORDER BY id DESC LIMIT 1';
        $res = DB::Instance()->query( $sql );
        $row = DB::Instance()->get_row($res);
        $poll = new Poll($row->id, $row);
        return $poll;
    }
}
?>
 
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Re: Poll script

Post by Skara »

turbolemon wrote:Change

Code: Select all

mysql_query("UPDATE poll_result SET YES = '{$row['Yes']}', NO = '{$row['No']}'");
to maybe:

Code: Select all

mysql_query("UPDATE poll_result SET YES = '$row[Yes]', NO = '$row[No]'");
PHP evaluates variables within double-quoted strings, as well as special characters ("\n", "\t", etc.).

Code: Select all

mysql_query("UPDATE poll_result SET YES = '{$row['Yes']}', NO = '{$row['No']}'");
^ is perfectly valid. Whatever the problem is, it isn't that.
Post Reply