Jump to content

Problem with simple vote script


BadGoat

Recommended Posts

Hello!

I am trying to get a small, simple script to work, starting easy, with a yes or no option vote. I much prefer to use MySQL to store the votes.  The script as it currently stands, does not insert the vote into the db. There are no errors, not sure what I am doing wrong.

code:[code]
<html>
<title>Vote!</title>
<head></head>
<body>
<form method="post" action="">
Please Vote:
<br />
Yes.<input type="radio" name="vote" value="yes">
<br />
No.<input type="radio" name="vote" value="no">
<br />
<input type="submit" value="Vote" name="submit">
</form>
</body>
</html>
<?php
error_reporting(E_ALL);
$connect= mysql_connect("*****", "*****")
    or die ("Could not connect to database!");
$result= mysql_select_db("*****")
    or die("Could not select that database !");

if (isset($_POST['vote'])) {

    $vote = $_POST['vote'];

    switch ($vote)
    {
        case 'yes':
            $query = 'UPDATE vote SET yes = yes + 1';
            break;

        case 'no':
            $query = 'UPDATE vote SET no = no + 1';
            break;

        default:
            print 'You didn\'t Vote';
            exit();
    }


    $result = mysql_query($query);
    if (!$result) {
        die('Query failed.'.$query.mysql_error());
    } else{
        printf('Thank you for Voting');
    }

    $query = 'SELECT * FROM vote';
    $result = mysql_query($query);
    if (!$result) {
        die('Query failed.'.$query.mysql_error());
    } else{
        $row = mysql_fetch_object($result);
        $total = $row->yes+$row->no;
        print 'Total votes recieved '.$total.;[/code]
Link to comment
https://forums.phpfreaks.com/topic/29523-problem-with-simple-vote-script/
Share on other sites

You cannot update something that is not there. You need to have a row already created to update it. Just insert one row first with values of 0 and your script will work fine. If not you would have to create a check to see if there are any rows then insert one. alot of wasted code if you only need one row and not have to do it again.

Ray

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.