PHP - Php Poll
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; } })();
Similar TutorialsHi 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> 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 I really made a poll system that allows users to voice their opinions within the community. Although the system is nearly complete, I can't seem to get the percentages working. Each option in the poll seems to have the incorrect percentage. I've tried several fixes but can't seem to get anything to work. :/ Current code: http://pastebin.com/dr6Ab1vR Picture of problem: What 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? What I'm wanting to do for the UPDATE statement is have it update the current value of answer_votes for that answer in that form to have it increase its value + 1 and increase the value of totalVotes for the specific poll +1 but not sure how that's accomplished. My table scheme is below. Code: [Select] if (isset($_POST['vote_poll'])) { $poll_quetion_id = mysqli_real_escape_string($dbc, $_POST['poll_question_id']); $poll_answer_id = (int) $_POST['id']; $voter_ip_address = $_SERVER["REMOTE_ADDR"]; $voter_ip_host = $_SERVER['HTTP_HOST']; $query = "SELECT * FROM `poll_answer_votes` WHERE ((`voter_ip_addess` = '".$voter_ip_address."') AND (`voter_ip_host` = '".$voter_ip_host."'))"; $Qresult = mysqli_query ( $dbc, $query ); // Run The Query if (mysqli_num_rows($Qresult) == 0) { $query = "INSERT INTO `poll_answer_votes` (poll_question_id, poll_answer_id, voter_ip_address, voter_ip_host, vote_time_stamp) VALUES ('".$poll_question_id."','".$poll_answer_id."','".$voter_ip_addres."','".$voter_ip_host."', NOW())"; mysqli_query($dbc, $query); $query = "UDPATE `poll_answers` SET "; mysqli_query($dbc, $query); $result = "good"; } else { } } Table: polls Fields: id, poll_question, total_votes Table: poll_answers Fields: id, poll_id, poll_answer, answer_votes Table: poll_answer_votes Fields: id, poll_question_id, poll_answer_id, voter_ip_address, voter_ip_host, vote_time_stamp. Hey, I need to make some sort of a survey, where on first page there's a poll, and second page is a form and submit. I've searched a bit, but I don't know exactly what to search for. It's important that there are several pages and clicking between them don't refresh the whole site, but only the part where the visitor i.e. clicks/submits. I appreciate of someone could point me in a direction for this. Many thanks Mathias I have a php poll page where the users need to cast their votes and the resut will be showed in a pie chart The questions and are taken from the database table poll_questions When the user cast his vote ,the vote for which answer along with the question should go to the database table poll_votes. I am using ajax for this. I am able to insert the vote to the database. but not able to insert the question to the database. Pasting my code here Code: [Select] poll_contest.php <?php include ('config.php'); ?> <html><head> <script type="text/javascript"> function getVote(int) { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5& +"&question="+q xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("poll").innerHTML=xmlhttp.responseText; } } var url="poll_vote.php"; url=url+"?vote="+int; //url=url+"&sid="+Math.random(); //var url="poll_vote.php?vote="+int+"&question="+q ; +"&question="+q //alert(q); xmlhttp.open("GET","poll_vote.php?vote="+int,true); xmlhttp.send(); } </script> </head> <body> <div id="poll"> <?php $ip=$_SERVER['REMOTE_ADDR']; echo "<table>"; $q="select * from polls_questions where id=(select max(id) from polls_questions)"; $r=mysql_query($q); $row=mysql_fetch_row($r); $poll_id = $row['id']; $question=$row['question']; echo "<input type='hidden' name='question' id='question' value=$question>"; echo "<tr><td>$row[1]</td></tr>". "<tr><td><input type='radio' value='1' name='answer' id='answer' onclick='getVote(this.value)'>$row[2]</td></tr>". "<tr><td><input type='radio' value='2' name='answer' id='answer' onclick='getVote(this.value)'>$row[3]</td></tr>". "<tr><td><input type='radio' value='3' name='answer' id='answer' onclick='getVote(this.value)'>$row[4]</td></tr>". "<tr><td><input type='radio' value='4' name='answer' id='answer' onclick='getVote(this.value)'>$row[5]</td></tr>". "</table>"; ?> </body> </html> poll_vote.php <?php include ('config.php'); $ip=$_SERVER['REMOTE_ADDR']; echo $ip; $vote = $_GET['vote']; $question=$_GET['question']; echo $vote; echo "<br>".$question; ?> Hi, i need help for get data from following tables:
questions:
id
question
options:
id
ques_id
value
votes:
id
option_id
voted_on
ip
Question: What is your favorite color.
Option1: Test 1 - 83 votes
Option2: Test 2 - 0 votes
Option3: Test 3 - 51 votes
I'm using this sql for result:
SELECT options.id, options.value, COUNT(*) as votes FROM votes, options WHERE votes.option_id=options.id AND votes.option_id IN(SELECT id FROM options WHERE ques_id=2) GROUP BY votes.option_id;so i get this: id value votes 1 Test1 83 3 Test3 51 because there is not votes for option Test2 and doesn't show it. i need help to get all data like this: id value votes 1 Test1 83 2 Test2 0 3 Test3 51 Hi All - hope someone has done this before. I need to create a PHP script that detects the presence of a new file appearing into a folder, and process it. This HAS to be supported by Windows IIS (Have looked at FAM for Linux but can't use it). I could do a loop with some sleep that checks the directory every x seconds - but this has been discounted by the client as either a) too resource hungry or b) not quick enough if there is a delay. Add ons, extensions or even external 3rd party tools would all be acceptable. Any ideas? Phil EDIT, CORRECTION- IT WENT TO MY JUNKMAIL. HOW DO I PREVENT THAT? ALSO, IT DID NOT PUT THE USER'S IP IN THE 'POSTER' FIELD IN DB SO I CAN PREVENT MULTIPLE POSTS PER PERSON. Hi, I went over the code and looks good to me, I put the "poster" field in my Members table. Everything looks good, my page loads with no errors, but the email never gets sent upon submitting the form "user poll" here is the relevant code, please any help greatly appreciated! thank you. Code: [Select] <?php if($_POST['submit']) { $currentPoster = $_SERVER['REMOTE_ADDR']; // get ip of visitor $query = mysql_query("SELECT * FROM members WHERE poster = '$currentPoster'"); //check DB for user ip if (mysql_num_rows($query) > 0) //if ip exists, user already posted { $error=1; //this is t o set if error message echoes or not. $errorMessage=" You already posted to this poll"; // echo error to the multiple post prick//echoed out below } else { $query2 = mysql_query("INSERT INTO members(poster) VALUES ('$currentPoster')");// insert new ip into DB $email_from = '.info POLL'; // email information $email_subject = " POLL RESPONDER"; $email_body = "You have received a new poll message from the user ip address of $currentPoster.\n". "Here is the message:\n $userfeedback"; //////////////////////////////////////////////////////////////////////// //SEND THE EMAIL $to = "xxxx@hotmail.com"; //email headers $headers = "From: $email_from \r\n"; $headers .= "Reply-To: no one \r\n"; mail($to,$email_subject,$email_body,$headers);// sends off the final email. $error=0; $goodmessage="Thank you for your feedback!"; } } ?> <form id="userfeedback" method="post" action="index.php"> <p> <textarea name="userfeedback" id="userfeedback" cols="45" rows="5"></textarea> <input type="submit" id="submit" name="submit"/> <input type="reset" id="reset" name="reset"/> </p> </form> <br/> <?php if($error=1) { echo $errorMessage; }else { echo $goodmessage; } ?> Hello I am looking to redesign an old poll system what approved to work effeciantly, however I now need to get the poll to work on my new site. I am getting these errors. Warning: mysql_query() [function.mysql-query]: Access denied for user 'nobody'@'localhost' (using password: NO) in /home/gaogier/public_html/includes/polls.php on line 4 Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/gaogier/public_html/includes/polls.php on line 4 Warning: mysql_query() [function.mysql-query]: Access denied for user 'nobody'@'localhost' (using password: NO) in /home/gaogier/public_html/includes/polls.php on line 52 Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/gaogier/public_html/includes/polls.php on line 52 Code is on pastebin - 24 hours. http://pastebin.com/1u19Xwwk Now here is where my files are located includes/connect.php includes/polls.php pages/ - my pages.php - displayed as a new folder almost using mod rewrite. tpl/sidebar.tpl - where my poll will be displayed using php - include. I'm trying to create a database driven poll to allow users to "like" or "dislike" each video on my site. But instead of radio buttons and a submit button I want to use images with jquery handling the submit when a choice is made. I have found 2 tutorials that each accomplish part of what I want. This tutorial has a poll which is perfect because I can pass in a poll id (which will be the same value as my video id) and it will load that video's poll. http://www.webresourcesdepot.com/ajax-poll-script-with-php-mysql-jquery/ This tutorial replaces the radio buttons with images. http://www.weblee.co.uk/2009/05/30/radio-button-replacement-with-style/ I have them both working separately on this page http://aaronhaas.com/poll2/ I can't seem to figure out how to combine the two together. The poll script generates its html inside of a php function. In the code below I have commented out the line ( getPoll(1) ) that calls the function and replaced it with the html it generates to make it easier to see what is going on. Another problem is each form has a different action so both actions somehow need to be combined together into a function. I was hoping someone might want to see if they can combine the two together and post it as a tutorial or demo. Code: [Select] <?php require("inc/db.php"); require("inc/functions.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Ajax Poll Script - Demo</title> <!-- styles and js for poll --> <script src="inc/js/jquery-1.4.2.min.js" type="text/javascript"></script> <script src="inc/js/poll.js" type="text/javascript"></script> <style> body { font-family: Arial, Helvetica, sans-serif; font-size: 1em; } #pollWrap{ width: 550px; margin-left:40px; } #pollWrap h3 { display:none; color:red; font-size: 1em; margin-bottom: 5px; display:none; } #pollWrap ul { margin: 0; padding: 0 0 0 5px; } #pollWrap li { padding: 0; /*overflow:hidden;*/ /*for our lovely friend IE6 to behave nicely*/ font-size: 0.8em; display: inline; } #pollWrap li span { font-size: 0.7em; } .pollChart { margin-left: 25px; height: 10px; width:1px; /*Adding rounded corners to the graphs - Optional - START*/ -moz-border-radius-topright: 4px; -moz-border-radius-bottomright: 4px; -webkit-border-top-right-radius: 4px; -webkit-border-bottom-right-radius: 4px; /*Adding rounded corners to the graphs - Optional - END*/ } #pollSubmit { margin-top: 5px; } #pollMessage { color:#C00; font-size: 0.8em; font-weight: bold; } </style> <!-- styles and js for image radio buttons --> <link rel="stylesheet" type="text/css" href="css/radio.css"> <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/radio-demo.js"></script> </head> <body> <div id="greenlight"> <div id="options"> <ul id="list"> <li class="active"><a href="#" class="option1 active" id="link1"><span>Option</span></a></li> <li><a href="#" class="option2" id="link2"><span>Option</span></a></li> </ul> </div> <!-- close options --> <form action="step2.html" method="post" id="radioform"> Green Light: <input name="option1" type="radio" value="option1" id="option1" checked="checked" /><br /> Cancel: <input name="option1" type="radio" value="option2" id="option2" /><br /> </form> <!-- <p><a href="#" class="toggleform">Show Hidden Form Radion Buttons</a></p> --> <?php // getPoll(1); //$pollID ?> <div id="pollWrap"> <form name="pollForm" method="post" action="inc/functions.php?action=vote"> <h3>Poll Question 1</h3> <ul> <li> <input name="pollAnswerID" id="pollRadioButton1" value="1" type="radio"> Answer1 for Poll1 <span id="pollAnswer1"></span> </li> <li class="pollChart pollChart1"></li> <li> <input name="pollAnswerID" id="pollRadioButton2" value="2" type="radio"> Answer2 for Poll1 <span id="pollAnswer2"></span> </li> <li class="pollChart pollChart2"></li> </ul> <input name="pollSubmit" id="pollSubmit" value="Vote" type="submit"> <span id="pollMessage"></span> <img src="ajaxLoader.gif" alt="Ajax Loader" id="pollAjaxLoader"> </form> </div> </div><!-- close greenlight --> </body> </html> This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=333432.0 Hey all, i have a problem; i have 2 arrays: $haystack //contains all posible answers in the poll, it contains dates for possible meetings Array ( => 12-02-2011 [1] => 13-02-2011 [2] => 14-02-2011 [3] => 15-02-2011 ) $needles //contains the answers the user clicked Array ( => 12-02-2011 [1] => 13-02-2011 ) i have about 10 entries simulated and i want to count the corresponding dates into another array so: Array ( => 5 [1] => 3 [2] => 1 [3] => 1 ) keep in mind that the users can give multiple answers I'm needing some direction in how to start this... I have a page with the 50 U.S. states listed. I have a column in my mysql database that holds each state's name called: source There's a few thousands rows in my database, so the state names vary in the record count. How can I query the database and have a little count by each one of my 50 states that shows how many results exist in the db for that state? I know how to query for total rows and show that number... but confused on how I would do it for individual line items. Thanks for any suggestions. 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. What I'm trying to do is have it select the answers that are associated to that poll so that I can make a poll form out of this. Code: [Select] function getpoll($dbc) { $query = " SELECT polls.ID, polls.question, polls.totalVotes, (SELECT pollAnswers.ID, pollAnswers.answer FROM pollAnswers WHERE pollAnswers.pollID = polls.ID) FROM polls INNER JOIN pollAnswers ON polls.ID = pollAnswers.pollID WHERE polls.statusID = '1' ORDER BY polls.ID DESC LIMIT 1"; $result = mysqli_query($dbc, $query); $numrows = mysqli_num_rows($result); if ($numrows > "0") { } else { print "<p class=none>There are currently no open polls."; } } I'm trying to create an object oriented PHP poll. I know I'm close but I got stuck. If anyone can help me with this. It's a radio button poll: Code: [Select] <html> <head> <title>Polling</title> <head> <body> <h1>Pop Poll</h1> <p>Who will you vote for in the election?</p> <form method=post action="show_poll.php"> <input type="radio" name="vote" value="John Smith">John Smith<br /> <input type="radio" name="vote" value="Mary Jones">Mary Jones<br /> <input type="radio" name="vote" value="Fred Bloggs">Fred Bloggs<br /><br /> <input type=submit value="Show results"> </form> </body> Here is the show_poll.php <?php /******************************************* Database query to get poll info *******************************************/ // get vote from form $vote=$_REQUEST['vote']; // log in to database if (!$db_conn = new mysqli('localhost', 'poll', 'poll', 'poll')) { echo 'Could not connect to db<br />'; exit; } if (!empty($vote)) // if they filled the form out, add their vote { $vote = addslashes($vote); $query = "update poll_results set num_votes = num_votes + 1 where candidate = '$vote'"; if(!($result = @$db_conn->query($query)))//'@' means not showing error message. { echo 'Could not connect to db<br />'; exit; } } else { echo 'You did not vote!<br />'; exit; } // get current results of poll, regardless of whether they voted $query = 'select * from poll_results'; if(!($result = @$db_conn->query($query))) { echo 'Could not connect to db<br />'; exit; } $num_candidates = $result->num_rows;//how many candidates are = the number of rows // calculate total number of votes so far $total_votes=0; while ($row = $result->fetch_object()) { $total_votes += $row->num_votes; } $result->data_seek(0); // reset result pointer ?> <h2>Result:</h2> <table> <tr> <td>John Smith:</td> <td> <img src="poll.gif" width='<?php echo(100*($num_candidates/$total_votes)); ?>' height='20'> <?php echo(100*($num_candidates/$total_votes)); ?>% </td> </tr> <tr> <td>Mary Jones:</td> <td> <img src="poll.gif" width='<?php echo(100*($num_candidates/$total_votes)); ?>'height='20'> <?php echo(100*($num_candidates/$total_votes)); ?>% </td> </tr> <tr> <td>Fred Bloggs:</td> <td> <img src="poll.gif" width='<?php echo(100*($num_candidates/$total_votes)); ?>'height='20'> <?php echo(100*($num_candidates/$total_votes)); ?>% </td> </tr> </table> the Problem:: When I click a candidate it increments the value in the database it gets recorded well but I have problem with showing the result. It doesn't show the result right. I know that the bug lays he Code: [Select] 100*($num_candidates/$total_votes)). Instead of $num_candidates variable I need to come up with another variable that is the number of votes each candidate gets. I don't know how to come up with that. Any help Please help me with this I'd like to have an object oriented solution the point is that I don't want to use "If else" statements. Thanks any help a lot in advance Hi, I'm currently using a voting script, but have a problem with people voting more then once, and want to add a way to keep the voting unique and 1 per person via IP check can anybody assist me how to implement it in the following script please?
<?php // the questions and the answers $pool_question="Do you think I should keep Galaxy Universe open?"; $pool_option[1]="Yes"; $pool_option[2]="No"; // If counter files are not available,they will be created // You may remove next lines after the first use of the script if (!file_exists("pool_5483543_1.txt")){ // next two lines will not work if writing permissions are not available // you may create the files bellow manualy with "0" as their unique content file_put_contents ("pool_5483543_1.txt",0); file_put_contents ("pool_5483543_2.txt",0); } // retrieve data saved in files $pool_responses[1]=file_get_contents("pool_5483543_1.txt"); $pool_responses[2]=file_get_contents("pool_5483543_2.txt"); // if user votes, increase corresponding value if ($_POST["5483543"] and $_POST["5483543b"]==""){ if ($_POST["5483543"]==1) {$pool_responses[1]++;file_put_contents("pool_5483543_1.txt",$pool_responses[1]);} if ($_POST["5483543"]==2) {$pool_responses[2]++;file_put_contents("pool_5483543_2.txt",$pool_responses[2]);} } // get percentajes for each answer in the pool // get total number of answers $total_responses=$pool_responses[1]+$pool_responses[2]; if ($total_responses==0){$total_responses=1;} // to avoid errors at start // compute percentajes (with one decimal number) $pool_percentaje[1] = round((100*$pool_responses[1])/$total_responses,1); $pool_percentaje[2] = round((100*$pool_responses[2])/$total_responses,1); // print the form, which includes de answers and the percentajes print "<center>\n"; print "<form method=post action=".$_SERVER["PHP_SELF"].">\n"; print "<b>".$pool_question."</b>\n"; print "<table cellpadding=4>\n<br>"; // answer 1 print "<tr>\n"; print "<td><input type=radio name=5483543 value=1> ".$pool_option[1]."</td>\n"; print "<td bgcolor=DDDDFF>" .$pool_responses[1]." (".$pool_percentaje[1]."%)</td>\n"; print "</tr>\n"; // answer 2 print "<tr>\n"; print "<td><input type=radio name=5483543 value=2> ".$pool_option[2]."</td>\n"; print "<td bgcolor=DDDDFF>" .$pool_responses[2]." (".$pool_percentaje[2]."%)</td>\n"; print "</tr>\n"; print "</table>\n"; // a simple control to avoid one user to vote several times if ($_POST["5483543"]){ print "<input type=hidden name=5483543b value=1>\n"; } print "<input TYPE=submit value=Add my answer>\n"; print "</form>\n"; print "</center>\n"; ?>The reason why I ask for IP check is I wan't to use $_SERVER["HTTP_X_MXIT_USERID_R"];in the place of the Ip since it give a unique name via the platform I want to implement it. Edited by cobusbo, 14 January 2015 - 01:49 PM. |