PHP - Making Anonymous Poll - Voting Only Once
So I have made an anonymous poll system but I would like to limit the possibility to vote only once from a single pc.
I think that I could store and check 3 things regarding a user that has voted: 1) $_SERVER['HTTP_CLIENT_IP']."!".$_SERVER['HTTP_X_FORWARDED_FOR']."!".$_SERVER['REMOTE_ADDR']; 2) HTTP cookie 3) Flash cookie LSO (because this contrary to the HTTP cookei can be detected in multiple browsers( (only if Flash is installed))) But there can be a simple situation - a simple user votes one time from Firefox and after a time his IP changes (for example he uses some Mobile internet where dynamic addressing is used) . Then for some reason he wants to use Internet Explorer where Flash is not installed. In result - it is possible to vote twice. Can anyone please suggest something regarding this? I know there is not 100% bulletproof solution - I just want to minimise the possibility to vote more than once. Also I am thinking about using EverCookie(undeletable cookie) but that could cause a lot of other problems. Similar TutorialsWhat would be the most efficient way of letting my administrators make a poll? I want them to be able to set how many options (all options will be a radiobutton) they wish to have in the poll. I'm basically stuck on the part of: how would I store the poll options. Would I make separate table then store all the questions in there with the ID of the poll they created? I am trying to run the function "age", using the last line, I thought that is how I could to access that method, but that doesn't work. Code: [Select] <?php require_once '../phpLive/phpLive.php'; $live->myClass = (object)array( "name" => "Billy Bob Joe", "age" => function($dob){ // Run some code } ); echo $live->myClass->age("1986-07-22"); ?> I get the following error when trying to do that. Quote Fatal error: Call to undefined method stdClass::age() in /xxx/new.plugin.php on line 9 Any Ideas how I can access that method? Thanks! I've always had an issue needing to write and maintain script to validate both client side and sever side so a while back I wrote a validation class whose primary purpose was: Accept in its constructor a JSON string which is mostly identical to the jQuery validation option except it also included a "sanitize" property. For instance: {"rules": {"account": {"minlength": 6}}, "messages": {"account": {"minlength": "Six numbers are required"}, "sanitize":{"account":int}}. Provide the correct jQuery validation option so a form can be validated client side. Sanitize the form data server side. Validate the form data server side.I recently looked at the code and it is a train wreck. I used a single class and had a bunch of protected functions where some would validate per a given rule and return the message upon error and others would sanitize. For non-typical rules required by the specific application, I would extend the class and add them. Some of these added rules required other resources such as an entities primary key, a PDO connection, etc. While inheritance worked fine to add simple rules, it did not do so for the rules which needed other resources. Also, even though I used "final" on my base class methods, I never liked this single class of many methods as I couldn't use the same name for a given rule and sanitize method (i.e. would rather use digit and digit instead of digit and int). I am thinking of changing it to something like the following. While this is definitely better, I question whether I should be using traditional classes to define my standard and custom rules. Any recommendations? Thanks class Validator { protected $options, $rules=[ "digit"=>function($value, $prop, $name){ return /*validate and return error string or null*/; }, "minlength"=>"ect, etc" ]; public function __construct(string $json, \Closure ...$customRules=[]) { $this->options=json_decode($json); $this->rules=array_merge($this->rules, $customRules); } } class Application { public function someMethod() { $pdo=$this->pdo; $applicationCustomRules=[ 'someCustomRule'=>function($value, $prop, $name) use ($pdo) { return /*validate and return error string or null*/; } ]; $validator=new Validator($json, ...$applicationCustomRules); //Which can be used such as: $jQueryOptions=$validator->getJQueryOptions(); $validator->validate($data); $validator->validateProperty('account', $account); } }
When using the phpDoc PHAR to parse the following file, it returns Parse Error: Syntax error, unexpected '(' on line 16 No summary was found for this file, and doesn't include the file. The specific script which triggers the error is ($this->prototype)(). I am using the PHAR listed on https://www.phpdoc.org/ which appears to be the same as https://github.com/phpDocumentor/phpDocumentor2/releases/download/v2.9.0/phpDocumentor.phar, and am running PHP 7.1.26. Any guess why I am getting this error? Recommended workarounds? As a hack, I am thinking of adding an ignored function or class who's only missing is to invoke the anonymous function. I've also tried using the PHAR at https://github.com/phpDocumentor/phpDocumentor2/releases/tag/v3.0.0-alpha.3, and while I don't get this error, I don't get any output. I first tried it without downloading the public key but got ssl errors. Is there more to in than just locating the two files in the same directory? Thanks <?php /** * My Summary. * * My Description. */ class Foo { private $prototype; public function __construct() { $this->prototype=function(){ return 'prototype';}; } public function getPrototype() { $prototype=($this->prototype)(); return $prototype; } } [michael@devserver test]$ php /usr/share/phar/phpDocumentor.phar -d ./phpDocDir -t ./phpDocTarget Collecting files .. OK Initializing parser .. OK Parsing files Parsing /var/www/public/test/phpDocDir/testphpdocs.php Parse Error: Syntax error, unexpected '(' on line 16 No summary was found for this file Storing cache in "/var/www/public/test/phpDocTarget" .. OK Load cache .. 0.001s Preparing template "clean" .. 0.011s Preparing 17 transformations .. 0.000s Build "elements" index .. 0.000s Replace textual FQCNs with object aliases .. 0.000s Resolve @link and @see tags in descriptions .. 0.000s Enriches inline example tags with their sources .. 0.000s Build "packages" index .. 0.000s Build "namespaces" index and add namespaces to "elements" .. 0.000s Collect all markers embedded in tags .. 0.000s Transform analyzed project into artifacts .. Applying 17 transformations Initialize writer "phpDocumentor\Plugin\Core\Transformer\Writer\FileIo" Initialize writer "phpDocumentor\Plugin\Twig\Writer\Twig" Initialize writer "phpDocumentor\Plugin\Graphs\Writer\Graph" Execute transformation using writer "FileIo" Execute transformation using writer "FileIo" Execute transformation using writer "FileIo" Execute transformation using writer "FileIo" Execute transformation using writer "FileIo" Execute transformation using writer "twig" Execute transformation using writer "twig" Execute transformation using writer "twig" Execute transformation using writer "twig" Execute transformation using writer "twig" Execute transformation using writer "twig" Execute transformation using writer "twig" Execute transformation using writer "twig" Execute transformation using writer "twig" Execute transformation using writer "twig" Execute transformation using writer "twig" Execute transformation using writer "Graph" 0.073s Analyze results and write report to log .. 0.000s [michael@devserver test]$
I have built a small classified ads application. A person can put in an item for sale and it will diaplay the item. On the input form for the ad they enter their email address.
I am looking for an application that will display an anonymous email address on the classified ad and send to the anonmmous email through to their real email address. I would prefer to do this through the web server of the client and not have to set up a Google Apps or third party email accout for the "catch all" account.
Any recommendation for tutorials to explain and illustrate how to write this code.
Thanks in advance for any assist.
m
Hello, I was wondering is it possible to create vote with php when people vote the voted thing will go away like for exsample if there is ingame map vote and players vote !map de_dust2 the de_dust2 will be removed from map list and the last map that stays will be used? Sorry for bad english. <form action='index.php' method='POST' enctype='multipart/form-dat'> <select name='votes'> <option>SEATOWN</option> <option>vote1</option> <option>vote2</option> <option>vote3</option> </select> <input type='submit' name='vote' value='Vote'> </form> <?php $vote=$_GET['votes']; if(isset($_POST['vote'])) { echo "voted"; echo $vote; } ?> why would this not echo out anything for $vote??? cheers matt This is a node voting module I created and it has a slight problem that I cannot figure out. It's supposed to be a simple 'Vote Up' or 'Vote Down' feature. You click 'Vote Up' and one appears in your vote tally. You click 'Vote Down' and your original vote tally is subtracted by one back down to zero. When it goes back to zero, it gets stuck there. It stays on zero no matter if I choose 'Vote Up' or 'Vote Down' again. There's something that's happening when I move my vote tally back down to zero. Maybe something isn't setup correctly with the $current_votes variable. I don't know. I've been at this for hours. Here's the code: <?php function bonnier_vote_perm() { return array('vote on content'); } function bonnier_vote_menu() { $items = array(); $items['vote'] = array( 'title' => 'vote', 'page callback' => 'bonnier_vote_vote', 'access arguments' => array('vote on content'), 'type' => MENU_CALLBACK, ); return $items; } function bonnier_vote_vote() { $nid = $_REQUEST['nid']; $value = $_REQUEST['votes']; $current_votes = db_result(db_query("SELECT votes FROM bonnier_vote WHERE nid = $nid")); if ($current_votes) { $new_votes = $current_votes + $value; db_query("UPDATE bonnier_vote SET votes = $new_votes WHERE nid = $nid"); } else { db_query("INSERT INTO bonnier_vote (nid, votes) VALUES ($nid, $value)"); } drupal_set_message('Your vote has been recorded'); drupal_goto('node/'.$nid); } function bonnier_vote_nodeapi(&$node, $op, $teaser = null, $page = null) { if ($op == 'view' && !$teaser) { $votes = db_result(db_query("SELECT votes FROM bonnier_vote WHERE nid = {$node->nid}")); if (!$votes) { $votes = 0; } $widget = '<div>'; $widget .= l('Vote Up', 'vote', array('query' => array('nid' => $node->nid, 'votes' => 1))); $widget .= ' '; $widget .= l('Vote Down', 'vote', array('query' => array('nid' => $node->nid, 'value' => -1))); $widget .= ' '; $widget .= 'Sco '. $votes; $widget .= '</div>'; $node->content['vote_widget'] = array( '#value' => $widget, '#weight' => -10, ); } } Any bit of advice would be much appreciated. Hi, I am trying to come up with the best way to create a range voting form. Each candidate will have a "confidence" value associated with the choice.(using a pulldown menu?) So for March Madness it would be: Team ....... Confidence Value..... each team could only be voted to finish the tournament in a particular place, and a value would be associated with that choice. The total choices possible determines the range of confidence value possible. So....if there are 16 teams to vote on....the confidence value would range from 1-16. The voter would assign his highest available value to the team he was most confident in landing in that particular position. Example: 16 teams - 16 conf vals - if certain Duke will end up at #1 - then vote : #1 = Duke, conf val 16 next, if almost as certain that NC will end up last - then vote: #16 = NC, conf val 15 next most certain "", conf val 14 and so on.... the tricky part is making sure that the form code validates each conf val so that it is used, but used on ly once.... ideally the form could return values that could then be imported into excel and comopared. has this been done somewhere? Can you help ? hope so.... thanks!! I'm trying to make a voting system, Where each person would vote and they'll receive a point for it. I just don't know how to accomplish this.. =/ Basically I am writing my own voting system but I have a few problems and I would like to address them all in one post rather than three. First: The first thing I need help with is using CURL to check if a user actually voted at the remote top list website. Two: I need maybe a source script of a 10 digit hash generator that will display the hash generated and will insert it into the database This is currently what my hash generator looks like but I need someone to help me change it so that it will echo the actual hash generated and inserts it into the database, <?php function gen_md5_password($len = 6) { return substr(md5(rand().rand()), 0, $len); } ?> Three: I need some sort of way to tell the database that if they hash is not used within 24 hours, it will just dump or delete. hi guys i am building a voting system for my gaming website people sign up for matches, and those will be played at 3-5 different maps people can vote for wich maps they want to play each player can choose 3 maps, also 3 x the same map now the results of that voting system are shown on the page like this There is 1 vote for Map 1 There are 5 votes for Map 2 There is 1 vote for Map 3 There are 2 votes for Map 7 There is 1 vote for Map 4 There is 1 vote for Map 5 There are 8 votes for Map 8 now i want to make a script that picks the maps that will be played, so only show the 3-5 best results in the example above it woud be 2 x map 8 and 1x map 2 but im not sure how to start on this the db table of the votes is built like this id matchid playerid mapid mapname 1 113 195 1 NukeTown 2 113 195 2 Grid 3 113 195 1 NukeTown 4 114 195 1 NukeTown 5 114 195 1 NukeTown any advice or thoughts on this? thanks Hello, Im trying to create a simple voting script for my site, i been trying different things but cannot get it too function properly. The idea is you click the 'thumbs up' image to add 1 to the 'likes' value and thumbs down to add '1' to the dislikes. Sound simple but its giving me headaches. Would really appreciate it if someone could take a quick look at my script. The table is called 'youtube_rating' (because thats the look i was going for) and in the table is 4 columns, id (aut0_increment), liked (counts liked votes), disliked (counts dislikes) and item_num which is the id for teh product the rating is for. Code: [Select] <? if ( $row['rating'] == 'YES' ) { require ("../rating/voting/dbcon.php"); $result1 = mysql_query("select * from youtube_rating WHERE item_num='".$page_id."'"); $row = mysql_fetch_array($result1); $dislike = $row['dislike']; $like = $row['liked']; if (isset($_POST['submitted'])) { require_once ("../database/functions.php"); $userip = $_SERVER['REMOTE_ADDR']; $id = safe($_POST['id']); $vote = '1'; // check if user already voted $result = mysql_query("SELECT * FROM youtube_ip WHERE userip='$userip' AND item_num ='".$id."'"); $num = mysql_num_rows($result); // if already voted show error if (isset($_POST['submitted']) && ($num > 0)) { echo '<div class="alreadyvoted">You have already voted!</div>'; } // add like if (isset($_POST['submitted']) && ($_POST['submitted'] == 'like') && ($num == 0)) { // add 1 to value $liked_value = mysql_query("SELECT liked FROM youtube_ip WHERE item_num ='".$id."'"); $liked_total = $liked_value + $vote; $query = "update youtube_rating set liked = '".$liked_total."' where item_num ='".$id."'"; echo '<div class="ilikethis">You like this!</div>'; } // add dislike if (isset($_POST['submitted']) && ($_POST['submitted'] == 'dislike') && ($num == 0)) { // add 1 to value $dislike_value = mysql_query("SELECT dislike FROM youtube_ip WHERE item_num ='".$id."'"); $dislike_total = $dislike_value + $vote; $query = "update youtube_rating set dislike = '".$dislike_total."' where item_num ='".$id."'"; echo '<div class="idislikethis">You Dislike this!</div>'; } // log ip // if (isset($_POST['submitted']) && ($num == 0)) // { // mysql_query ("insert into youtube_ip (userip, item_num) values ('".$userip."', '".$id."')"); // } } ?> <table width="50%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="48%" align="center"> <form action="" method="post"> <input name="id" type="hidden" value="<? echo $page_id ?>" /> <input name="submitted" type="hidden" value="like" /> <button type="submit" class="like_button" name="like" id="like" > <img src="../rating/voting/pixel-vfl73.gif" alt=""> <span><?php echo $like?></span> </button> </form> </td> <td width="52%"> <form action="" method="post"> <input name="id" type="hidden" value="<? echo $page_id ?>" /> <input name="submitted" type="hidden" value="dislike" /> <button type="submit" class="dislike_button" name="dislike" id="dislike" > <img src="../rating/voting/pixel-vfl73.gif" alt=""> <span><? echo $dislike?></span> </button> </form> </td> </tr> </table> <? } ?> The problem is the vote does not add up or update the database, also it doesn't seem to be checking if the user has voted or not, it just attempts (but fails) to add a vote no matter what Thanks for any help. Hi there, im hoping someone can help me with this. What i’m trying to do is prevent users from voting twice with cookies, ive tried to set several myself but none of them have worked. Any help would be amazing. Thanks. EDIT: unsure why its formatted this way. how to fix?
<?php include 'functions.php'; // Connect to MySQL $pdo = pdo_connect_mysql(); // If the GET request "id" exists (poll id)... if (isset($_GET['id'])) { // MySQL query that selects the poll records by the GET request "id" $stmt = $pdo->prepare('SELECT * FROM polls WHERE id = ?'); $stmt->execute([$_GET['id']]); // Fetch the record $poll = $stmt->fetch(PDO::FETCH_ASSOC); // Check if the poll record exists with the id specified if ($poll) { // MySQL query that selects all the poll answers $stmt = $pdo->prepare('SELECT * FROM poll_answers WHERE poll_id = ?'); $stmt->execute([$_GET['id']]); // Fetch all the poll anwsers $poll_answers = $stmt->fetchAll(PDO::FETCH_ASSOC); // If the user clicked the "Vote" button... if (isset($_POST['poll_answer'])) { // Update and increase the vote for the answer the user voted for $stmt = $pdo->prepare('UPDATE poll_answers SET votes = votes +1 WHERE id = ?'); $stmt->execute([$_POST['poll_answer']]); // Redirect user to the result page header ('Location: result.php?id=' . $_GET['id']); exit; } } else { die ('Poll with that ID does not exist.'); } } else { die ('No poll ID specified.'); } ?> <?=template_header('Poll Vote')?> <div class="content poll-vote"> <h2><?=$poll['title']?></h2> <p><?=$poll['des']?></p> <form action="vote.php?id=<?=$_GET['id']?>" onSubmit="disable()" method="post"> <?php for ($i = 0; $i < count($poll_answers); $i++): ?> <label> <input type="radio" name="poll_answer" value="<?=$poll_answers[$i]['id']?>"<?=$i == 0 ? ' checked' : ''?>> <?=$poll_answers[$i]['title']?> </label> <?php endfor; ?> <div> <input type="submit" name="submit" value="Vote"> <a href="result.php?id=<?=$poll['id']?>">View Result</a> </div> </form> </div> <?=template_footer()?> Edited July 1, 2020 by requinix cleaning up post I made a website for school where everyone can upload their summaries, download them and rate them (thumbs up, thumbs down). You upload a summary with some data: a specific class, subject, name etc. The path to the file, the name, subject etc. comes in a mysql table and the summaries show in a list on the site. Now here comes the problem, when you vote a summary up you go to the page up.php like this: Code: [Select] <!--Directing to up.php--> --some mysql-- while ( $summary = mysql_fetch_assoc($result) ) { echo "<a href=\"up.php?id=".$summary['id']."&page=".$summary['class'].$summary['period']."\">"; } On the page up.php I have the following code which adds +1 in the thumbsup row in myqsl: Code: [Select] <!-- thumbsup +1 --> --some mysql-- $sql2 = "UPDATE locatie SET thumbsup = thumbsup + '1' WHERE id='".strval($_GET['id'])."'"; $uitvoeren2 = mysql_query($sql2); and sends you back to the previous page Code: [Select] header("Location: ".$_GET['page'].".php"); Google crawls all my pages, and also the page Code: [Select] up.php?id=1&page=class1periode3, which changes my mysql. Leading to that all of the summaries are being voted on by google, which is every annoying. This probably isn't the best voting script but I'm fairly new to php and thought this up on my own, so I was wondering if I could get it working properly Thanks in advance Hello everyone. I recently coded a Minecraft Voting for Diamonds script. Basically, you enter your username, you vote on the sites, then click "Get Reward". The reward then goes through a RCON script, and rewards the user with their diamonds in-game. the full script works fine, and I am happy with it, but there is one small problem; and that is users being able to abuse the system. If they wanted to, they could just refresh the page, and click Get Rewarded again, and again. I want to make something like this: It has a countdown on the link, which is started upon click, and then the link re-activates when the timer is done. My script already has "disabled=..." tags, so you have to click all links, this way would make sure a user cannot click the link until the timer is done. I'm pretty new to PHP, and please forgive me if it is not 100% PHP, but this place seemed extremely helpful. I am also pretty new to PHP, so make it for dummies xD Thanks everyone! Hi Guys, I am designing this website that takes votes on images. I need to store the votes for each image against the image name and a username. For this purpose, I need to modify the current code which retrieves votes from the voting system but doesn't have a system to enter the image name dynamically. Below is the code for the same: Code: [Select] <?php ob_start(); $host="localhost"; $username="computat_abhi"; $password="[..]"; $databasename="computat_button"; $tbl_name="record"; $db=mysql_connect ("localhost", "computat_abhi", "[..]")or die(mysql_error()); mysql_select_db($databasename, $db) or die(mysql_error()); if( isset($_POST['Like']) ) { $sql = 'INSERT INTO record(ImageNumber,LikeCounter) VALUES (\'b1\', 1)'; mysql_query($sql, $db) or die(mysql_error()); echo 'Like vote is registered'; } elseif(isset($_POST['Dislike'])) { $sql = 'INSERT INTO record(ImageNumber,DislikeCounter) VALUES (\'b1\', 1)'; mysql_query($sql, $db) or die(mysql_error()); echo 'Dislike vote is registered'; } ob_end_flush(); ?> <html> <head> <title> Do you Like/Dislike this image? </title> </head> <body> <h1> Do you Like/Dislike this image? </h1> <form name="form1" method ="post"> <input type="submit" name="Like" value="Like"> <input type="submit" name="Dislike" value="dislike"> </form> </body> </html> Another issue is to register a new user on the website www.computationalphotography.in and link it with the voting system above. Looking forward to your help and suggestions. Hello. I am trying to code a voting poll in php, but don't know how to get started. I came across a javascript type quiz that seems to do what I have in mind, but it needs to be tweaked and coded in php. The reason being that anyone can browse the javascript source code and cheat. Anyhow please see the attached files that show what I am trying to accomplish. The code has 3 files index.html, quiz.css and quiz.js
<html> <head> <title>Website - Voting Poll (Javascript)</title> <link rel="stylesheet" href="quiz.css"> <link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet"> </head> <body> <div id="container"> <h1>Voting Poll >> In Less Than A Minute</h1> <br/> <div id="quiz"></div> <div class="button" id="next"><a href="#">Next</a></div> <div class="button" id="prev"><a href="#">Prev</a></div> </div> <script src="https://code.jquery.com/jquery-3.4.0.min.js"></script> <script src="quiz.js"></script> </body> </html> body { font-family: 'Josefin Sans', sans-serif; } h1 { text-align: center; } .button { width: 80px; height: 25px; text-align: center; float:right; background-color: #fff; margin: 0 2px 0 2px; cursor: pointer; } .button a { text-decoration: none; color: #555; line-height: 25px; } #container { width:50%; margin: 150px auto; padding: 50px 30px; background-color: #3f51b5; border-radius:3px; color: #fff; box-shadow: 0 0 10px 0 #999; } ul { list-style-type: none; padding: 0; margin: 0; width: 500px; } ul li { background: #223394; width: 200px; margin: 10px; padding: 5px; display: inline-block; } #prev { display:none; } #start { display:none; width: 100px; } input[type="radio"]{ cursor: pointer; } (function() { var allQuestions = [{ question: "IMAGE 1 .jpg goes here", options: ["Yes", "No"], answer: 0 }, { question: "IMAGE 2 .jpg goes here", options: ["Yes", "No"], answer: 1 }, { question: "IMAGE 3 .jpg goes here", options: ["Yes", "No"], answer: 1 },{ question: "IMAGE 4 .jpg goes here", options: ["Yes", "No"], answer: 0 }, { question: "IMAGE 5 .jpg goes here", options: ["Yes", "No"], answer: 1 },{ question: "IMAGE 6 .jpg goes here", options: ["Yes", "No"], answer: 0 }]; var quesCounter = 0; var selectOptions = []; var quizSpace = $('#quiz'); nextQuestion(); $('#next').click(function () { chooseOption(); if (isNaN(selectOptions[quesCounter])) { alert('Please select an option !'); } else { quesCounter++; nextQuestion(); } }); $('#prev').click(function () { chooseOption(); quesCounter--; nextQuestion(); }); function createElement(index) { var element = $('<div>',{id: 'question'}); var header = $('<h2>Question No. ' + (index + 1) + ' :</h2>'); element.append(header); var question = $('<p>').append(allQuestions[index].question); element.append(question); var radio = radioButtons(index); element.append(radio); return element; } function radioButtons(index) { var radioItems = $('<ul>'); var item; var input = ''; for (var i = 0; i < allQuestions[index].options.length; i++) { item = $('<li>'); input = '<input type="radio" name="answer" value=' + i + ' />'; input += allQuestions[index].options[i]; item.append(input); radioItems.append(item); } return radioItems; } function chooseOption() { selectOptions[quesCounter] = +$('input[name="answer"]:checked').val(); } function nextQuestion() { quizSpace.fadeOut(function() { $('#question').remove(); if(quesCounter < allQuestions.length) { var nextQuestion = createElement(quesCounter); quizSpace.append(nextQuestion).fadeIn(); if (!(isNaN(selectOptions[quesCounter]))) { $('input[value='+selectOptions[quesCounter]+']').prop('checked', true); } if(quesCounter === 1) { $('#prev').show(); } else if(quesCounter === 0) { $('#prev').hide(); $('#next').show(); } } else { var scoreRslt = displayResult(); quizSpace.append(scoreRslt).fadeIn(); $('#next').hide(); $('#prev').hide(); } }); } function displayResult() { var score = $('<p>',{id: 'question'}); var correct = 0; for (var i = 0; i < selectOptions.length; i++) { if (selectOptions[i] === allQuestions[i].answer) { correct++; } } score.append('Final TOTAL is ' + correct + ' out of ' +allQuestions.length); return score; } })();
My code: Code: [Select] <?php if ($_REQUEST['poll_question']){ include 'database_info.php'; //Seeing how many options were filled in switch ($_REQUEST['poll_question']){ case ($_REQUEST['option_4'] != ''): $options = $_REQUEST['option_1'] ." | ".$_REQUEST['option_2'] ." | ".$_REQUEST['option_3'] ." | ".$_REQUEST['option_4']; break; case ($_REQUEST['option_3'] !=''): $options = $_REQUEST['option_1'] ." | ".$_REQUEST['option_2'] ." | ".$_REQUEST['option_3']; break; case ($_REQUEST['option_2'] !=''): $options = $_REQUEST['option_1'] ." | ".$_REQUEST['option_2']; break; case ($_REQUEST['option_1'] !=''): die("The poll needs more then one option."); break; mysql_query = ("INSERT INTO poll VALUES ('','".mysql_real_escape_string($_REQUEST['poll_question']."', '".mysql_real_escape_string($options)."', ".time().")"); echo "The poll has been created."; }else{ <form name="poll_submit" action="<?php $_SERVER[PHP_SELF];?>" method="POST"> Poll Question: <input type="text" name="poll_question"> <br /> Poll Options: <br /> <input type="text" name="option_1"> <br /> <input type="text" name="option_2"> <br /> <input type="text" name="option_3"> <br /> <input type="text" name="option_4"> <br /> <input type="submit"> </form> } ?> What did I do wrong? I get this error. Code: [Select] Parse error: syntax error, unexpected '=' in /home/moviefli/spambb.com/index.php on line 83 Hi I tried to make a poll system but it's not working, when you submit the option it doesn't get added to the database and I don't know what I'm doing wrong. This is my polls.php Code: [Select] <?php if (isset($_POST['go']) && $_POST['go']=='Vote') { if (!isset($_POST['choice']) || !isset($_POST['current_poll'])) { $error = 'You did not select an answer'; } if (empty($_POST['choice']) || empty($_POST['current_poll'])) { $error = 'You need to select an answer'; } else { $sql ='UPDATE poll_answers SET votes = votes + 1 WHERE poll_id="'.$_POST['current_poll'].'" AND id="'.$_POST['choice'].'"'; mysql_query ($sql) or die ('SQL error !'.$sql.'<br />'.mysql_error()); mysql_close (); $error = 'Thank you for your answer :)'; } } ?> <html> <head> </head> <body> <?php $sql = 'SELECT id, questions FROM polls'; $req = mysql_query ($sql) or die ('SQL error !<br />'.$sql.'<br />'.mysql_error()); $data = mysql_fetch_array ($req); $votes = mysql_num_rows($req); if ($votes == 0) { echo 'No survey.'; } else { mysql_free_result ($req); echo stripslashes(htmlentities(trim($data['questions']))),'<br />'; echo '<form action = "polls" method = "post">'; $sql = 'SELECT id, answers FROM poll_answers WHERE poll_id="'.$data['id'].'"'; $req = mysql_query($sql) or die('SQL Error !<br />'.$sql.'<br />'.mysql_error()); while ($donnees = mysql_fetch_array($req)) { echo '<input type="radio" name="choice" value="' , $donnees['id'] , '"> ' , stripslashes(htmlentities(trim($donnees['answers']))) , '<br />'; } ?> <input type = "hidden" name = "current_poll" value = "<?php echo $data['id']; ?>"> <input type = "submit" name="Submit" value = "Submit"> </form> <?php } mysql_free_result ($req); mysql_close (); ?> <br /><br /> <a href="test">See the result</a> <?php if (isset($error)) echo '<br /><br />',$error; ?> </body> </html> and this is my test.php Code: [Select] <html> <head> </head> <body> <?php $sql = 'SELECT id, questions FROM polls ORDER BY id DESC LIMIT 0,1'; $req = mysql_query ($sql) or die ('error SQL !<br />'.$sql.'<br />'.mysql_error()); $data = mysql_fetch_array ($req); $votes = mysql_num_rows($req); mysql_free_result ($req); if ($votes == 0) { echo 'No opinion poll.'; } else { echo stripslashes(htmlentities(trim($data['questions']))),'<br />'; $picture_responses = array(); $picture_nb_reponses = array(); $sql = 'SELECT answers, votes FROM poll_answers WHERE poll_id="'.$data['id'].'"'; $req = mysql_query($sql) or die('error SQL !<br />'.$sql.'<br />'.mysql_error()); while ($data = mysql_fetch_array($req)) { $picture_responses[] = $data['answers']; $picture_nb_reponses[] = $data['votes']; } mysql_free_result ($req); mysql_close (); $nb_reponses_of_opinion_poll = count ($picture_responses); $nb_total_reponse = array_sum ($picture_nb_reponses); if ($nb_total_reponse == 0) { echo 'No vote '; } else { for ($i = 0; $i < $nb_reponses_of_opinion_poll; $i++) { echo $picture_responses[$i]; $percentage = ($picture_nb_reponses[$i] * 100) / $nb_total_reponse; $percentage = round ($percentage, 1); echo ' ',$percentage,' %<br />'; } echo '<br /><br />Number of answers : ', $nb_total_reponse; } } ?> </body> </html> |