Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

update not working 1

Status
Not open for further replies.

Sardamil

Programmer
Apr 14, 2001
77
NL
I'm trying to update a field in a table using a radio button. For some reason it's not working and I've no idea why? Can anybody help me please? Posting the login.php too as I think that might be relevant.


login.php
<?php

//Betekent dat er met sessies word gewerkt

ob_start();
session_start();

/* Dit document heet: login.php */


//Met database connecten

$host = 'xxxxx'; //Host

$gebruikersnaam = 'xxxxx'; //Gebruikersnaam

$wachtwoord = 'xxxxx'; //Wachtwoord

$database = 'xxxxx'; //Database



/* Alle gegevens met belangrijk: Een mysql_error() dat geeft een foutmelding aan als de gegevens fout zijn*/

mysql_connect($host, $gebruikersnaam, $wachtwoord);

mysql_select_db($database) or die(mysql_error());



//Simpele loginformulier in html

$loginform = '

<h4>Inloggen</h4><br>

<form action="login.php" method="post">

Id:<br>

<input type="text" name="speler" /><br>

Wachtwoord:<br>

<input type="password" name="wachtw" /><br>

<input type="submit" name="login" value="Log in" />

</form>';



//Als er geklikt is op "login"

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



//Kijken of alle velden zijn ingevuld.

if(empty($_POST['speler']) || empty($_POST['wachtw'])){

//Zoniet, geef foutmelding.

echo 'Het inloggen ging verkeerd of je hebt nooit ingelogd1!';

exit();

}

//De gebruikersnaam en het wachtwoord in een var zetten

$speler = $_POST['speler'];

$wachtw = md5($_POST['wachtw']);



//Query maken om alle gegevens op te halen.

$query = sprintf("SELECT * FROM spelers WHERE user = '%s' AND wachtwoord = '%s' LIMIT 1;", mysql_real_escape_string($speler), mysql_real_escape_string($wachtw));

//Query uitvoeren

$uitvoeren = mysql_query($query) or die('Er ging iets fout bij de query! Raporteer de webmaster hier over!');

//Kijken of er rijen zijn met de gegevens die zijn ingevoerd

$result = mysql_num_rows($uitvoeren);

//Als de rij er niet is(0)

if($result = 0){



//Geef foutmelding

echo 'Het inloggen ging verkeerd of je hebt nooit ingelogd2!';

echo $loginform;



//Else.. Anders.

}

else

{



//Zet sessies

$_SESSION['ingelogd'] = 1;

$_SESSION['gb'] = $speler;

header('Location: aanwezig.php');
exit();
}

}

//Anders

else

{

//Laat loginform zien

echo $loginform;

}
ob_end_flush();
?>

aanwezigcode.php:
<?php
//Betekent dat er met sessies word gewerkt
session_start();

/* Deze pagina heet: aanwezigcode.php */

//Connecteren met wedstrijden

$mysqlhost = 'xxxxx'; //Host

$mysqlgebruikersnaam = 'xxxxx'; //Gebruikersnaam

$mysqlwachtwoord = 'xxxxx'; //Wachtwoord

$mysqldatabase = 'xxxxx'; //Database



$conn1 = mysql_connect($mysqlhost, $mysqlgebruikersnaam, $mysqlwachtwoord);

mysql_select_db($mysqldatabase) or die(mysql_error());


//Query opstellen om gegevens uit de database te halen.
$que = "SELECT * FROM wedstrijden";
//Query uitvoeren
$uitvoeren1 = mysql_query($que) or die(mysql_error());

// de table beginnen
echo '
<A HREF = logout.php>Log out</A>
<table>
<tr>
<td width="130">Datum</td>
<td width="180">Thuis</td>
<td width="180">Uit</td>
<td width="300">Aanwezig</td>';

//rij maken zodat je gegevens kan gebruiken
while($rij = mysql_fetch_assoc($uitvoeren1)){
//Echo(laat zien simpel form)
array_map('htmlspecialchars', $rij);
echo '
<form action="aanwezig.php" method="POST">
</tr>
<tr>
<td width="130">'.$rij['datum'].'</td>
<td width="180">'.$rij['thuis'].'</td>
<td width="180">'.$rij['uit'].'</td>
<td width="300"><input type="radio" name="aanwezig" value="aanwezig" />Aanwezig
<input type="radio" name="aanwezig" value="afwezig"/>Afwezig
<input type="submit" name="submit" value="Verstuur" /></td>';

// en tenslotte de boel afsluiten
echo '
</tr>
</table>;
</form>';
}
//Even een dingetje opstellen voor de database
$wedstrijdid = $_POST['wedstrijdid'];
//Als form verstuurd is
if( isset($_POST['submit'])){
//Connecteren met aanwezigheid

$host = 'xxxxx'; //Host

$gebruikersnaam = 'xxxxx'; //Gebruikersnaam

$wachtwoord = 'xxxxx'; //Wachtwoord

$database = 'xxxxx'; //Naam database

$conn = mysql_connect($host, $gebruikersnaam, $wachtwoord);
mysql_select_db($database) or die(mysql_error());
//Een query maken en beveiligen met mysql_real_escape_string

$query = " UPDATE aanwezigheid
SET aanwezigheid = '".mysql_real_escape_string($_POST['aanwezig'])."'
where spelerid= (select s.spelerid from spelers s where s.user = '".mysql_real_escape_string($_SESSION['gb'])."')
and wedstrijdid = '".mysql_real_escape_string($_POST['wedstrijdid'])."'";

$uitvoeren = mysql_query($query) or die(mysql_error());
}
?>

Murphy's Law said:
Anything that can go wrong will go wrong

Window to my world
 
sorry, I misunderstood.

CREATE TABLE IF NOT EXISTS `spelers` (
`idspeler` smallint(5) NOT NULL auto_increment,
`naam` varchar(40) NOT NULL default '',
`wachtwoord` varchar(65) NOT NULL default '',
`user` varchar(65) NOT NULL default '',
`lastLoginTime` int(15) NOT NULL default '0',
PRIMARY KEY (`idspeler`)
) TYPE=MyISAM AUTO_INCREMENT=23 ;

INSERT INTO `spelers` (`idspeler`, `naam`, `wachtwoord`, `user`, `lastLoginTime`) VALUES
(2, 'Peter', 'test', 'user 1', 1251474163)

CREATE TABLE IF NOT EXISTS `wedstrijden` (
`idwedstrijd` smallint(5) NOT NULL auto_increment,
`datum` date NOT NULL default '0000-00-00',
`thuis` varchar(20) NOT NULL default '',
`uit` varchar(20) NOT NULL default '',
PRIMARY KEY (`idwedstrijd`)
) TYPE=MyISAM AUTO_INCREMENT=38 ;

INSERT INTO `wedstrijden` (`idwedstrijd`, `datum`, `thuis`, `uit`) VALUES
(1, '2009-08-23', 'Sportclub WVV ''28 2', 'Daalhof 5'),
(2, '2009-08-27', 'Daalhof 5', 'SVME 4'),
(3, '2009-08-30', 'Oranje Boys 2', 'Daalhof 5'),
(4, '2009-09-06', 'Daalhof 5', 'Keer 4'),
(5, '2009-09-13', 'Berg''28 5', 'Daalhof 5'),
(6, '2009-09-20', 'Daalhof 5', 'RKUVC 4'),
(7, '2009-09-27', 'RKASV 5', 'Daalhof 5'),
(8, '2009-10-04', 'Daalhof 5', 'Heer 4'),
(9, '2009-10-11', 'SV Meerssen 4', 'Daalhof 5'),
(10, '2009-10-18', 'Daalhof 5', 'DBSV 4'),
(11, '2009-10-25', 'Beker', 'Inhaal'),
(12, '2009-11-01', 'RKVVL/Polaris 6', 'Daalhof 5'),
(13, '2009-11-08', 'I.B.C.''03 2', 'Daalhof 5'),
(14, '2009-11-15', 'Daalhof 5', 'Geulsche Boys 2'),
(15, '2009-11-22', 'Beker', 'Inhaal'),
(16, '2009-11-29', 'Schimmert 3', 'Daalhof 5'),
(17, '2009-12-06', 'Keer 4', 'Daalhof 5'),
(18, '2009-12-13', 'Daalhof 5', 'Berg''28 5'),
(19, '2009-12-20', 'Beker', 'Inhaal'),
(20, '2010-01-17', 'Beker', 'Inhaal'),
(21, '2010-01-24', 'Beker', 'Inhaal'),
(22, '2010-01-31', 'Beker', 'Inhaal'),
(23, '2010-02-07', 'Beker', 'Inhaal'),
(24, '2010-02-14', 'Beker', 'Inhaal'),
(25, '2010-02-21', 'Beker', 'Inhaal'),
(26, '2010-02-28', 'RKUVC 4', 'Daalhof 5'),
(27, '2010-03-07', 'Daalhof 5', 'RKASV 5'),
(28, '2010-03-14', 'Heer 4', 'Daalhof 5'),
(29, '2010-03-21', 'Beker', 'Inhaal'),
(30, '2010-03-28', 'Daalhof 5', 'SV Meerssen 4'),
(31, '2010-04-03', 'Beker', 'Inhaal'),
(32, '2010-04-05', 'DBSV 4', 'Daalhof 5'),
(33, '2010-04-11', 'Daalhof 5', 'RKVVL/Polaris 6'),
(34, '2010-04-18', 'Daalhof 5', 'I.B.C.''03 2'),
(35, '2010-04-25', 'Geulsche Boys 2', 'Daalhof 5'),
(36, '2010-04-30', 'Beker', 'Inhaal'),
(37, '2010-05-02', 'Daalhof 5', 'Schimmert 3');

CREATE TABLE IF NOT EXISTS `aanwezigheid` (
`spelerid` int(5) NOT NULL default '0',
`wedstrijdid` int(5) NOT NULL default '0',
`aanwezigheid` varchar(20) NOT NULL default 'aanwezig',
PRIMARY KEY (`spelerid`,`wedstrijdid`)
) TYPE=MyISAM;

(2, 37, 'aanwezig'),
(2, 36, 'aanwezig'),
(2, 35, 'aanwezig'),
(2, 34, 'aanwezig'),
(2, 33, 'aanwezig'),
(2, 32, 'aanwezig'),
(2, 31, 'aanwezig'),
(2, 30, 'aanwezig'),
(2, 29, 'aanwezig'),
(2, 28, 'aanwezig'),
(2, 27, 'aanwezig'),
(2, 26, 'aanwezig'),
(2, 25, 'aanwezig'),
(2, 24, 'aanwezig'),
(2, 23, 'aanwezig'),
(2, 22, 'aanwezig'),
(2, 21, 'aanwezig'),
(2, 20, 'aanwezig'),
(2, 19, 'aanwezig'),
(2, 18, 'aanwezig'),
(2, 17, 'aanwezig'),
(2, 16, 'aanwezig'),
(2, 15, 'aanwezig'),
(2, 14, 'aanwezig'),
(2, 13, 'aanwezig'),
(2, 12, 'aanwezig'),
(2, 11, 'aanwezig'),
(2, 10, 'aanwezig'),
(2, 9, 'aanwezig'),
(2, 8, 'aanwezig'),
(2, 7, 'aanwezig'),
(2, 6, 'aanwezig'),
(2, 5, 'afwezig'),
(2, 4, 'aanwezig'),
(2, 3, 'aanwezig'),
(2, 2, 'aanwezig'),
(2, 1, 'aanwezig')

Murphy's Law said:
Anything that can go wrong will go wrong

Window to my world
 
this is a bit rough around the edges, but it should give you an idea of how to make the whole thing work.

Code:
<?php
session_start();
//Betekent dat er met sessies word gewerkt
/* Dit document heet: login.php */

define('USERTABLE', 'spelers');
define('LOGINEXPIRES', true);	//set to true in order to 'time out' users after TIMEOUT seconds
define('TIMEOUT', 900);	//depending on LOGINEXPIRES, sets the timeout value to 15 minutes.
define('STORELOGININDB', true); //set to true in order to store the last login time in the database.  you will need a column called lastLoginTime (int(15))
define('DEBUG', true);	//set to false for production user
define('DEBUGFILE', './debugfile.txt');
if (DEBUG){
	error_reporting(E_ALL);
	ini_set('display_errors', true);
} else {
	ini_set('display_errors', false);
}

/**
 * function to connect to the db. 
 * 
 * this only needs to be called ONCE per script.
 * @return 
 */

function dbConnect(){
	//Met database connecten 
	$host =                     'localhost'; //Host
	$gebruikersnaam =     'root'; //Gebruikersnaam
	$wachtwoord =             'root'; //Wachtwoord
	$database =             'gamepresence'; //Database
	/* Alle gegevens met belangrijk: Een mysql_error() dat geeft een foutmelding aan als de gegevens fout zijn*/
	
	mysql_connect($host, $gebruikersnaam, $wachtwoord); 
	mysql_select_db($database) or mysql_bail(mysql_error(), 'select db'); 
}

/**
 * this function starts the motor.  
 * 
 * nothing else is needed as if logged in you want this whole script to be silent. login failures etc automatically display the login form with appropriate messages and then kill the script execution
 *  
 * @return 
 */
function startLoginProcess(){
	if (isLogout()){
		logout();
		displayLoginForm('You have been logged out');
	}
	if(isLoggedIn()){
		updateLastLogin();
	} else {
		//not logged in
		//so check login attempt
		checkLogin();
	}
}


/**
 * helper function to display the login form.
 * if this is a second/subsequent login attempt, the username field is prefilled
 * 
 * @param object $message [optional] 
 * @return void
 */
function displayLoginForm($message = null){
	if (!empty($message)){
		$message = "<div id=\"loginMessage\">$message</div>";
	}
	$speler = empty($_POST['speler']) ? '' : $_POST['speler'];
	echo <<<HTML
	<h4>Inloggen</h4><br>
	$message 
	<form action="{$_SERVER['PHP_SELF']}" method="post"> 
		Id:<br/> 
		<input type="text" name="user" value="$speler" /><br> 
		Wachtwoord:<br> 
		<input type="password" name="wachtwoord" /><br> 
		<input type="submit" name="login" value="Log in" /> 
	</form>
HTML;
	exit;
}


/**
 * helper function to determine whether a user has already logged in
 * @return 
 */
function isLoggedIn(){
	if (empty($_SESSION['loggedIn']) || $_SESSION['loggedIn'] !== true){
		return false;
	}
	if (!empty($_GET['logout'])){
		logout();
		displayLoginForm('You have been logged out');
	}
	if (logInExpired()){
		logout();
		displayLoginForm('Your login has expired. Please log in once more');
	} else {
		return true;
	}
}


/**
 * helper function to validate the login form data and fork off as required
 * 
 * @return 
 */
function checkLogin(){
	if (!empty($_POST['login'])){
		if (empty($_POST['user']) || empty($_POST['wachtwoord'])){
			//data not provided
			displayLoginForm('You must provide a username and password');
		} else {
			//data provided
			$isValid = validateCredentials($_POST['user'], $_POST['wachtwoord']);
			if (!$isValid){
				displayLoginForm('Either your username or password is incorrect');
			} else {
				logIn($_POST['user']);
			}
		}
	} else {
		displayLoginForm();
	}
}


/**
 * helper function to retrieve the user credentials for a given username
 * 
 * @param object $user
 * @return	associative array of userdata
 * ToDo: filter the return data
 */
function getUserCredentials ($user){
	$sql = "select * from " . USERTABLE .' where naam=%s';
	$user = dbReady($user);
	$query = sprintf($sql, $user);
	$result = mysql_query($query) or mysql_bail(mysql_error(), $query);
	return mysql_fetch_assoc($result);
}

/**
 * helper function to set the log-in flags and session data
 * @param object $user
 * @return 
 */
function logIn($user){
	$credentials = getUserCredentials($user);
	$_SESSION['loggedIn'] = true; 
	$_SESSION['userData'] = $credentials;
	
	//import from OP code
	$_SESSION['ingelogd'] = 1; 
	$_SESSION['gb'] = $user;
	updateLastLogin();
}

/**
 * helper function to update the time that the user was last seen.
 * 
 * data is stored in both the session table and the user table (in a column called lastLoginTime);
 * @return 
 */
function updateLastLogin(){
	$_SESSION['lastLogIn'] = time();
	if (STORELOGININDB){
		if (!dbHasColumn(USERTABLE, 'lastLoginTime')){
			addDBColumn(USERTABLE, 'lastLoginTime', 'int(15) not null default 0');
		}
		$sql = 'update '. USERTABLE . ' set lastLoginTime=%d where idspeler=%s';
		$query = sprintf($sql, $_SESSION['lastLogIn'], dbReady($_SESSION['userData']['idspeler']));
		mysql_query($query) or mysql_bail(mysql_error(), $query);
	}
}

/**
 * helper function to add a column to table
 * @param object $table	the table to alter
 * @param object $column the name of the column to add
 * @param object $definition the column definition
 * @return 
 */
function addDBColumn($table, $column, $definition){
	$query = "ALTER TABLE $table ADD COLUMN $column $definition";
	mysql_query($query) or mysql_bail(mysql_error(), $query);
}


/**
 * helper function to check whether database has a particular column in it
 * @param object $table
 * @param object $column
 * @return true if the column exists, false otherwise/
 */
function dbHasColumn ($table, $column){
	$query = "show columns in $table like '$column'";
	$result = mysql_query($query) or mysql_bail (mysql_error(), $query);
	$row = mysql_fetch_assoc($result);
	return $row;
}


/**
 * helper function to determine whether a user's login has timed out.
 * @return true for a timeout, false otherwise.
 */
function logInExpired(){
	if( ! LOGINEXPIRES)	return false;
	if (empty($_SESSION['lastLogIn'])) return true;
	return (($_SESSION['lastLogIn'] + TIMEOUT) < time());
}


/**
 * helper function to check whether the user is authorised to access the system
 * 
 * @param object $user
 * @param object $pwd
 * @return (bool) true if authorised, false if not
 */
function validateCredentials($user, $pwd){
	$sql = "Select count(*) as cnt from " .USERTABLE ." where user=%s and wachtwoord=%s";
	$params = array($user, encode($pwd));
	$params = array_map('dbReady', $params);
	$query = vsprintf($sql, $params);
	$result = mysql_query($query) or mysql_bail(mysql_error(), $query);
	$row = mysql_fetch_assoc($result);
	return ($row['cnt'] != 1);
}


/**
 * helper function to encode data in md5/sha4 etc
 * 
 * @param object $data
 * @return encoded data or false on error
 */
function encode($data){
	return md5($data); 
}


/**
 * helper function to enquote and return escaped data for mysql usage
 * 
 * @param object $data
 * @return 
 */
function dbReady($data){
	//trim the data
	$data = trim($data);
	if (function_exists('mysql_real_escape_string')){
		$result = @mysql_real_escape_string($data);
		if (!$result){
			$result = mysql_escape_string($data);
		}
	} else {
		$result = mysql_escape_string($data);
	}
	return "'". $result. "'";	
}

/**
 * function to handle logouts
 * @return 
 */
function logout(){
	unset($_SESSION);
	session_destroy();
}

function isLogout(){
	return (isset($_REQUEST['logout']));
}
function mysql_bail($error, $query){
	$time = date('r');
	$message = <<<HTML
<h2>Mysql Error</h2>
<div id="message">
$error
</div>
<div id="query">
Query was 
<pre>$query</pre>
</div>
<div id="timestamp">
Timestamp: $time
</div>
HTML;
	file_put_contents(DEBUGFILE, $message, FILE_APPEND);
	if (DEBUG){
		echo $message;
		exit;
	} else {
		echo "An unrecoverable error has occurred.  The administrator has been informed.  Please try back later.";
		exit;
	}
}

dbConnect();
startLoginProcess(); //that's all folks!
?>

Code:
<?php
require_once './login.php';
function displayGameGrid($message = null){
	// de table beginnen
	if (!empty($message)){
		$message = "<div id=\"errorMessage\">$message</div>";
	}
	echo <<<HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml"[/URL] xml:lang="en" lang="en">

<head>
	<meta http-equiv="content-type" 
		content="text/html;charset=utf-8" />
	<meta http-equiv="Content-Style-Type" content="text/css" />
<title>Game Presence Indicator</title>
 <link type="text/css" href="[URL unfurl="true"]http://jqueryui.com/latest/themes/base/ui.all.css"[/URL] rel="stylesheet" />
<script type="text/javascript" src="{$_SERVER['PHP_SELF']}?action=inclJQuery"></script>
<script type="text/javascript" src="[URL unfurl="true"]http://jqueryui.com/latest/ui/ui.core.js"></script>[/URL]
<script type="text/javascript" src="[URL unfurl="true"]http://jqueryui.com/latest/ui/ui.slider.js"></script>[/URL]
<script type="text/javascript" src="[URL unfurl="true"]http://jquery.offput.ca/js/jquery.highlightFade.js"></script>[/URL]
<script type="text/javascript">
/* Copyright (c) 2008 Kean Loong Tan [URL unfurl="true"]http://www.gimiti.com/kltan[/URL]
 * Licensed under the MIT ([URL unfurl="true"]http://www.opensource.org/licenses/mit-license.php)[/URL]
 * Copyright notice and license must remain intact for legal use
 * jFade
 * Version: 1.0 (Jun 30, 2008)
 * Requires: jQuery 1.2.6+
 * 
 *
 * Original Code Copyright (c) 2008 by Michael Leigeber
 * Website: [URL unfurl="true"]http://www.leigeber.com[/URL]
 * 
 *
 */ 
(function(A){A.fn.jFade=function(N){var B=A.extend({},A.fn.jFade.defaults,N);var F,C,K,E,H,J,I,M,D;var G=this;var L=function(){var Q=G;B.steps=B.steps||20;B.duration=B.duration||20;clearInterval(Q.timer);C=O(B.end);K=C[0];E=C[1];H=C[2];if(!Q.r){F=O(B.start);r=F[0];g=F[1];b=F[2];Q.r=r;Q.g=g;Q.b=b}J=Math.round(Math.abs(Q.r-K)/B.steps);I=Math.round(Math.abs(Q.g-E)/B.steps);M=Math.round(Math.abs(Q.b-H)/B.steps);if(J==0){J=1}if(I==0){I=1}if(M==0){M=1}Q.step=1;Q.timer=setInterval(function(){P(Q,B.property,B.steps,K,E,H,J,I,M)},B.duration);function P(V,d,a,e,U,X,c,Y,f){var T=V;var S;if(T.step<=a){var R=T.r;var W=T.g;var Z=T.b;if(R>=e){R=R-c}else{R=parseInt(R)+parseInt(c)}if(W>=U){W=W-Y}else{W=parseInt(W)+parseInt(Y)}if(Z>=X){Z=Z-f}else{Z=parseInt(Z)+parseInt(f)}S="rgb("+R+","+W+","+Z+")";A(V).css(d,S);T.r=R;T.g=W;T.b=Z;T.step=T.step+1}else{clearInterval(T.timer);S="rgb("+e+","+U+","+X+")";A(V).css(d,S)}}function O(R){var S=[parseInt(R.substring(0,2),16),parseInt(R.substring(2,4),16),parseInt(R.substring(4,6),16)];return S}};if(B.trigger=="load"){L()}else{A(this).bind(B.trigger,function(){G=this;L()})}return this};A.fn.jFade.defaults={trigger:"load",property:"background",start:"FFFFFF",end:"000000",steps:5,duration:30}})(jQuery);
</script>
<script type="text/javascript">
function sliderTransform(elem, val){
	val = val=='aanwezig' || val == 1 ? 0 : 1;
	jQuery('#' + elem + ' > .slider').slider({
		animate: true,
		max: 1,
		min: 0,
		orientation: 'horizontal',
		step: 1,
		value: val,
		stop: function(e, i){
			updateDB(e, i);
		}
	});
}
function updateDB(e, i){
	var ival = (i.value == 1) ? '0' : '1';
	var idBits = jQuery(e.target).closest("td").attr('id').split('_');
	jQuery("#form_" + idBits[1] + " input[name=aanwezig]:radio").val([ival]);
	var $frm = jQuery("#form_" + idBits[1]);
	var data = $frm.serialize() + '&isAjax=true';
	var url = $frm.attr('action');
	jQuery.post(url, data, function(data){
		if(data.result == 'ok'){
			alert('fading');
			jQuery("#" + data.elem).highlightFade({	start:'#7df173',speed:3000});
		}
	} , 'json');
}
function init(){
	jQuery("span.control").each(
					function(){
						var id = this.id;
						jQuery("#r_" + id).css("display", "none");
						jQuery("#r_" + id + ' > input[name=aanwezig]:radio').bind('change', function(e){
							alert('i am changed');
						});
						var val = jQuery("#r_" + id + ' > input:radio:checked').val();
						sliderTransform(id, val);
					});
} /* end function */
jQuery(document).ready(init);
</script>
<style type="text/css">
html, body, table, td, tr, th, div, span, a, li, ul,ol{padding:0; margin:0}
#header{background-color:#423605; color:#e9fae3; text-align:right; padding-right: 15px;}
#header a{color:#e9fae3; text-decoration:none;}
#header a:visited; #header a:active {color:#e9fae3; text-decoration:none;}
#header a:hover {font-weight: bolder;}
#wrap {width:70%; margin: 0 auto; margin-top: 40px;}
#wrap, input {font-family:"Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif; font-size: 0.75em}
th,td {text-align:left;}
th.centre, td.centre {text-align:center;}
.alt{background-color:#e3eeff;}
h3{text-align:center; color:#2d36fd;}

.ui-slider { position: relative; margin: 2px auto;}
.ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; }
.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; }
.ui-slider-horizontal { height: 1.5em; text-align:center; width:3em; }
.ui-slider-horizontal .ui-slider-handle {  height:100%; top:-0.1em;}
.ui-widget{font-size:0.9em;}
div.center{margin: 0 auto; overflow:hidden;text-align:center;}
div.left {float:left; padding: 0px 0.5em;}
</style>
</head>
<body>
<div id="header">
You are logged in as {$_SESSION['userData']['naam']}. <a class="logout" href="{$_SERVER['PHP_SELF']}?logout">Logout here</a>
</div>
<div id="wrap">
$message
<h3>Game Attendance for {$_SESSION['userData']['naam']}</h3>
<table>
	<thead>
    <tr>
        <th width="130">Datum</td>
        <th width="180">Thuis</td>
        <th width="180">Uit</td>
        <th width="300" class="centre">Aanwezig<br/>(Yes <-> No)</td>
	</tr>
	</thead>
	<tbody>
HTML;

	//Query opstellen om gegevens uit de database te halen.
	$sql = "SELECT date_format( w.datum, '%%D %%b %%Y') as d, w.* , a.aanwezigheid as present
			FROM  `wedstrijden` w
			JOIN aanwezigheid a ON ( a.wedstrijdid = w.idwedstrijd ) 
			WHERE a.spelerid = %s";
	
	$query = sprintf($sql, dbReady($_SESSION['userData']['idspeler']));
	$result = mysql_query($query) or mysql_bail(mysql_error(), $query);
	//rij maken zodat je gegevens kan gebruiken
	$class='';
	while($rij = mysql_fetch_assoc($result)){
	    array_map('htmlspecialchars', $rij);
		//set initial state
		if ($rij['present'] == 'aanwezig' || $rij['present'] == '1'){
			$_aanwezig = 'checked="checked"';
			$_afwezig = '';
		} else {
			$_afwezig = 'checked="checked"';
			$_aanwezig = '';
		}
		$class = ($class=='alt') ? '' : 'alt';
	    echo <<<HTML
			<tr class="$class">
				<td width="130">{$rij['d']}</td>
				<td width="180">{$rij['thuis']}</td>
				<td width="180">{$rij['uit']}</td>
				<td width="300" id="d_{$rij['idwedstrijd']}" class="centre" align="center">
					<form action="{$_SERVER['PHP_SELF']}" method="POST" id="form_{$rij['idwedstrijd']}">
						<input type="hidden" name="gameID" value="{$rij['idwedstrijd']}" />
						<input type="hidden" name="action" value="updateGame" />
						<span class="control" id="{$rij['idwedstrijd']}">
							<span class="radio" id="r_{$rij['idwedstrijd']}" >
							<input type="radio" name="aanwezig" value="1" $_aanwezig />&nbsp;Aanwezig
							<input type="radio" name="aanwezig" value="0" $_afwezig />&nbsp;Afwezig
							</span>
							<div class="slider" id="slider_{$rij['idwedstrijd']}">
							</div>				
						</span>
					</form>
				</td>
			</tr>
HTML;
	}	//end while
		echo <<<HTML
		
			</tbody>
		</table>
		</div>
		</body>
HTML;
} //end function

function updateGameGrid(){
	//validate input
	if (empty($_POST['gameID']) || empty($_POST['aanwezig'])){
		return false;
	} else {
		$result = updateGameTable($_POST['gameID'], $_POST['aanwezig'], $_SESSION['userData']['idspeler']);
		if ($result === false){
			$message = 'something went wrong updating the game table';
		} else {
			$message = 'ok';
		}
		return $message;
	}
}

function updateGameTable($gameID, $present, $player){
	$sql = "replace 
			into aanwezigheid 
			set aanwezigheid=%s,spelerid=%s, wedstrijdid=%s";
	$params = array($present, $player, $gameID);
	$params = array_map('dbReady', $params);
	$query = vsprintf($sql, $params);
	$result = mysql_query($query) or mysql_bail(mysql_error(), $query);
	return $result;	
}

/**
 * helper function to determine what we need to do on the page
 * @return 
 */
function getAction(){
	return  empty($_POST['action'])
				? (empty($_GET['action']) 
					? ''
					: trim($_GET['action']) )
				: trim ($_POST['action']);
}


/**
 * helper function to determine whether db update request is an ajax request or not.
 * @return 
 */
function isAjax(){
	return (!empty($_POST['isAjax']));
}

/**
 * helper function to cache jQuery in the local filesystem
 * 
 * @return 
 */
function cacheJQuery(){
	$url = '[URL unfurl="true"]http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js';[/URL]
	$ch = curl_init($url);
	curl_setopt_array($ch, array(CURLOPT_RETURNTRANSFER=>true));
	$file = curl_exec($ch);
	if (strlen($file) > 0 ){
		file_put_contents('jQuery.js', $file);
	}
}

$action = getAction();
switch ($action){
	case 'updateGame':
		$result = updateGameGrid();
		if (isAjax()){
			echo json_encode(array('result'=>$result, 'elem'=> 'd_' . $_POST['gameID']));
			exit;
		} else {
			displayGameGrid($result);
		}
	break;
	case 'inclJQuery':
		$c = 0;
		clearstatcache();
		while (!file_exists('jQuery.js')){
			if ($c > 10){
				echo 'cannot get the file';
				exit;
			}
			cachejQuery();
			$c++;
		}
		readfile ('jQuery.js');
		break;
	default:
		displayGameGrid();
}
?>
 
I've been trying to find this variable $frm, but can't find it.

Notice: Undefined variable: frm in /var/ on line 59

Notice: Undefined variable: frm in /var/ on line 60

Notice: Undefined variable: frm in /var/ on line 107

Firebug says:
missing variable name
[Break on this error] var = jQuery("#form_" + idBits[1]);\ngamePresence.php (line 56)

Murphy's Law said:
Anything that can go wrong will go wrong

Window to my world
 
oh darn. the problems of cross platform debugging.

it works on my machine (bar one error which should not throw a warning).

the reason why you are getting the error is that i included the javascript in the body of the page for the tek-tips post. whereas on my machine i kept it as a separate file.

can you cut the js from the file, put into a separate file called js.js and then add this line to gamepresence

Code:
<script type="text/javascript" src="js.js" ></script>

and also change this line

Code:
if (empty($_POST['gameID']) || empty($_POST['aanwezig'])){

to
Code:
if (empty($_POST['gameID']) || !isset($_POST['aanwezig'])){
 
That solved that problem. Now I just get an empty screen with only the headers. I think one of the variables is empty as ot also doesn't show a name at the top. ("you're logged in as.")

Will have to look into that after the match.

Murphy's Law said:
Anything that can go wrong will go wrong

Window to my world
 
Two things
1 empty your browser cache
2 make sure your db schema is precisely as you posted here.
 
I gave you an export of the tables, so you should have had the correct db schema. Will empty the browser cache and have another look at it.

Murphy's Law said:
Anything that can go wrong will go wrong

Window to my world
 
In login.php I changed
sql = "select * from " . USERTABLE .' where naam=%s';

into
sql = "select * from " . USERTABLE .' where user=%s';

That fixed the problem. Still no update though. Checking firebug now. Can't get firebug to work properly. Keeps asking me to reload.

As aanwezigheid is a character field, should (in function updateGameTable) this "set aanwezigheid=%s" not be "set aanwezigheid='%s'"?

Murphy's Law said:
Anything that can go wrong will go wrong

Window to my world
 
there is no need to enquote database fields. the dbReady function does that.

the updates will be happening. in firebug check the net panel. if firebug is not working, upgrade it to the latest version (as well as firefox).

if you still cannot get things working i will upload to one of my public servers so you can see how things work in practice.
 
From firebug's net panel. When I change a radiobutton nothing happens in firebug.

GET ui.slider.js

304 Not Modified

jquery-ui.googlecode.com

14 KB


379ms
ParamsHeadersPostPutResponseCacheHTML
Response Headers
Date Sun, 30 Aug 2009 12:51:28 GMT
Server Apache
Etag "2652//tags/latest/ui/ui.slider.js"
Request Headers
Host jquery-ui.googlecode.com
User-Agent Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.13) Gecko/2009080315 Ubuntu/9.04 (jaunty) Firefox/3.0.13
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 300
Connection keep-alive
Referer If-Modified-Since Thu, 04 Jun 2009 11:54:54 GMT
If-None-Match "2652//tags/latest/ui/ui.slider.js"
Cache-Control max-age=0
Load Response
GET jquery.highlightFade.js

304 Not Modified

jquery.offput.ca

7 KB


937ms
ParamsHeadersPostPutResponseCacheHTML
Response Headers
Date Sun, 30 Aug 2009 12:51:29 GMT
Server Apache
Connection Keep-Alive
Keep-Alive timeout=2, max=100
Etag "653c277-1d57-43417b0ec2200"
Request Headers
Host jquery.offput.ca
User-Agent Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.13) Gecko/2009080315 Ubuntu/9.04 (jaunty) Firefox/3.0.13
Accept */*
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 300
Connection keep-alive
Referer If-Modified-Since Sat, 30 Jun 2007 04:04:24 GMT
If-None-Match "653c277-1d57-43417b0ec2200"
Cache-Control max-age=0

Murphy's Law said:
Anything that can go wrong will go wrong

Window to my world
 
you should not have radio buttons on display.

i will post the code up on my site in about an hour. check back here for the url.
 
that should work. I cannot see if it updates the database though.
I didn't see the slider, but I still get the radiobuttons for some reason.

Murphy's Law said:
Anything that can go wrong will go wrong

Window to my world
 
One thing though, is it possible to replace the slider by a checkbox or the radiobuttons. I'm not sure if people will understand the slider. If not, that's ok. I'll just have to explain clearly what they need to do.

Murphy's Law said:
Anything that can go wrong will go wrong

Window to my world
 
please take a look at the site again. i have replaced the slider with a more straightforward alternative.

yes: a checkbox is very simple to integrate in place of the slider. in fact it is already there - you should need to turn a variable off in the code.
 
it's not working. It looks like what I got before I changed this in login.php
sql = "select * from " . USERTABLE .' where naam=%s';

into
sql = "select * from " . USERTABLE .' where user=%s';

no names are shown now and no detailrecords.

Murphy's Law said:
Anything that can go wrong will go wrong

Window to my world
 
please use Peter/test for the username and password as posted.

the site works seamlessly for me on FF and safari and chrome (mac beta).

 
this is what the page should look like

screenshot.png
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top