Hello! Does anyone know of a tutorial which increments an integer in a database every time a button is clicked? I have looked at voting scripts on the net and they are all far too complicated, I was hoping to be able to reverse engineer it to be able to figure out how to do this on a simplistic small scale which would fit my learning needs, but alas.
Seeking a counter-type tutorial
I can't recommend a tutorial, but here is a script I made a long time ago for a simple yes/no vote. It should give you some idea.
SQL Table
CREATE TABLE `vote` (
`yes` int(3) NOT NULL default '0',
`no` int(3) NOT NULL default '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
<?php
error_reporting(E_ALL);
define('_HOST', 'localhost');
define('_USER','edit_user_here'); //edit
define('_PASS','edit_password_here'); //edit
define('_DB','edit_database_here'); //edit
define('_BR',"\n<br />");
if (isset($_POST['vote'])) {
$vote = $_POST['vote'];
$link = mysql_connect(_HOST,_USER,_PASS);
$db = mysql_select_db(_DB, $link);
/* check connection */
if (!$link) {
die('Could not connect: ' . mysql_error());
}
/* Check database*/
if (!$db) {
die ('Can\'t use '._DB.' : ' . mysql_error());
}
//////////////////////////////////////////////////////////////////////////////
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,$link);
if (!$result) {
die('Query failed.'.$query.mysql_error());
} else{
printf('Thank you for Voting');
}
$query = 'SELECT yes, no FROM vote';
$result = mysql_query($query,$link);
if (!$result) {
die('Query failed.'.$query.mysql_error());
} else{
$row = mysql_fetch_object($result);
$total = $row->yes+$row->no;
$yesPercentage=$row->yes/$total*100;
$noPercentage=$row->no/$total*100;
print 'Total votes recieved '.$total._BR;
print 'Total Yes votes recieved '.$row->yes."\t\t\t\t-->".round($yesPercentage,2).'%'._BR;
print 'Total No votes recieved '.$row->no."\t\t\t\t-->".round($noPercentage,2).'%'._BR;
}
}
?>
<html>
<title>Voting Page</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>
Many thanks for the example, picking through it now!