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 .= 'Score: '. $votes;
$widget .= '</div>';
$node->content['vote_widget'] = array(
'#value' => $widget,
'#weight' => -10,
);
}
}
Any bit of advice would be much appreciated.