Here is some sample code taken from a project that I implemented recently. It used a hidden field to pass the id $form_id and also tries an insert before update (not all rows are required in the voting table).
Hope it helps.
In terms of cookies to ensure voting only once. Realize that any client-side mechanism can be easily bypassed through the use of a cookie manager. I'd recommend either a registration and login process. Then you could store the fact that a vote was made in a table associated with the userid (a separate table allows for an easy mechanism to allow multiple votes).
Glen
<?php
//////////////////////////////////////////////////////////////////////////////
// Copyright Glen Bernstein, 2002 (Glen@TheBernsteins.US)
// This code may be used and modified freely, as long as credit is given to
// its original author.
//////////////////////////////////////////////////////////////////////////////
require_once 'DB.php';
// Setup Database variables
$user = 'dbuser';
$pass = 'password';
$host = 'localhost';
$db_name = 'dbname';
$table = 'ranktable';
$fields = array ('votes', 'id');
// Retrieve value from submitted form
$id = $form_id;
// Data Source Name: This is the universal connection string
$dsn = "mysql://$user:$pass@$host/$db_name";
// DB::connect will return a PEAR DB object on success
// or an PEAR DB Error object on error
$db = DB::connect($dsn, true);
// With DB::isError you can differentiate between an error or a valid connection.
if (DB::isError($db))
{
die ($db->getMessage());
}
else
{
print ('Connected!<br>');
}
// Prepare database statements
$insert = $db->prepare("INSERT INTO $table ($fields[0], $fields[1]) VALUES (?, ?)");
$select = $db->prepare("SELECT $fields[0] FROM $table WHERE $fields[1]=?");
$update = $db->prepare("UPDATE $table SET $fields[0]=? WHERE $fields[1]=?");
$record = array (1, $id);
// First attempt to insert a new record
$result = $db->execute($insert, $record);
if (DB::isError($result))
{
// Insert failed, check to see if record exists
if ($result->getCode() == DB_ERROR_ALREADY_EXISTS)
{
// Record exists, select and update
$result = $db->execute($select, $record[1]);
if (DB::isError($result))
{
die ($result->getMessage());
}
else
{
// Select succeeded, increment vote count and update
$row = $result->fetchrow();
$votes = $row[0];
$record[0] += $votes;
$result = $db->execute($update, $record);
if (DB::isError($result))
{
die ($result->getMessage());
}
else
{
print ('updated<br>');
}
}
}
else
{
die ($result->getMessage());
}
}
else
{
print ('inserted<br>');
}
// You can disconnect from the database with:
$db->disconnect();
?>