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 gkittelson 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
 
this line
Code:
if($result = 0){

is wrong. read up on the difference between = and == and ===

you should also consider using an optimised count(*) query in lieu of a select * query.
 
I tried looking for it, but couldn't find anything. Could be becasue it was 5 am and I was about to go to work.

I did however try to change it to if($result == 0){ , but that gave me 0 as a result from the query. Before the login seemed to work. I hope you are willing to explain what you mean.

I used the select *, because that table only has 37 records and I need all of the table. Why do you think I should use a count?

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

Window to my world
 
For the simple version try:

For the detail see the manual:

I see from your stats that you've been a member for 8 years and asked 13 questions, but you have only had 2 answers that you have marked as valuable. If you have really only had 2 good answers, read faq222-2244 to see how to ask better questions. If you have had more good answers, see faq222-2244 to see how to recognise them, and to guide other users to good answers.

If you want the best response to a question, please check out FAQ222-2244 first.
'If we're supposed to work in Hex, why have we only got A fingers?'
Drive a Steam Roller
 
Has it been that long?
It's not that I don't think that the comments are valuable. I'm ussualy just to preoccupied with the problem to think about clicking the valuable button.

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

Window to my world
 
the line should be
Code:
$result == 0
or even better
Code:
$result !== 1

$result, in this case, holds the number of rows returned against the uname/password lookup. therefore if there is 0 rows, there is no match and if there is more than 1 row then there are too many matches as the uname should be unique.

if it was working before but not after the change then this is because it will have ALWAYS worked before, irrespective of the input uname and password.

i do not agree with the concept of 'redirect on logon' either. i believe it is better to script your login functions so that they protect at a page level. once page level protection is implemented you can then very easily extend your structure to allow more granular functional level controls.

a page level protection scheme is implemented by creating your protection script in a known file (such as login.php) and then adding this line as the start of every page that a user can access

Code:
require_once 'path/to/login.php';

and that's it. another easier way of doing this, that is potentially safer, is to edit your php.ini file (or upload one for your base directory) with this directive in it
Code:
auto_prepend_file 'path/to/login.php'

this can also be done by way of .htaccess file.
this is my recommended method.

i have recast your code in a better style. you will find it MUCH easier to code properly if you break down each aspect of your script into separate functions. In time, you will doubtless move from a procedural style function set into a class. In fact, a set of user functions such as these lend themselves almost perfectly to a class, but i have left as procedural code for the time being.

this code also provides for auto timeouts. if you set the relevant definition to true the code will automatically create the necessary columns in your table too.

you will NOT need to connect to the database, or start sessions anywhere else in your code. equally with this script, and the auto_prepend you do NOT need to use output buffering (which should be avoided unless you actively are planning to use output buffering properly).

style tip: code in english, with english variables, column names and comments. this will make it more globally maintainable in the future.

health warning: this code has not been tested - i typed it straight in to an IDE and have no knowledge of whether there are syntax, logic or other errors. if they exist, they are easily solvable.

Code:
<?php
//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

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 =                     '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 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(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="speler" 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();
	}
	if (logInExpired()){
		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['speler']) || empty($_POST['wachtwoord'])){
			//data not provided
			displayLoginForm('You must provide a username and password');
		} else {
			//data provided
			$isValid = validateCredentials($_POST['speler'], $_POST['wachtwoord']);
			if (!$isValid){
				displayLoginForm('Either your username or password is incorrect');
			} else {
				logIn($_POST['speler']);
			}
		}
	} 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 user=%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 user=%s';
		$query = sprintf($sql, $_SESSION['lastLogIn'], dbReady($_SESSION['userData']['name']));
		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));
	array_map('dbReady', $params);
	$query = vpsrintf($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 "'$data'";	
}

/**
 * function to handle logouts
 * @return 
 */
function logout(){
	$_SESSION['isLoggedIn'] = false;
	unset($_SESSION['userData']);
	displayLoginForm('You have been logged out');
}

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!
?>


and i have also recast your game presence script using the same kind of functional separation, and javascript to communicate the database updates.

i am concerned that this will not work because the query parameters do not look like they are proper table names/columns. for example, why would you call a table aanwezigheid? that looks like a column name instead. equally, without you having actually posted your table schemas i can only guess as to what they might be.

the same health warning applies to this code as to the previous.

Code:
<?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>
	<title>An XHTML 1.0 Strict standard template</title>
	<meta http-equiv="content-type" 
		content="text/html;charset=utf-8" />
	<meta http-equiv="Content-Style-Type" content="text/css" />
</head>

<head>
<title>Game Presence Indicator</title>
<meta 	http-equiv="content-type" 
		content="text/html;charset=utf-8" />
<script type="text/javascript" src="{$_SERVER['PHP_SELF']}?action=inclJQuery"></script>
<script type="text/javascript">
function init(){
	/* set all the form cells to green to show clean */
	jQuery("td.frm").css('background-color', '#cdfbb5');

	jQuery("form input:radio").bind('click', function(e){
		e.preventDefault(); /* should not be necessary */
		e.stopPropagation();
		/* set table cell to red to show that it is dirty */
		jQuery(this).closest('td').css("background-color", '#f8c4a9');
		jQuery.post(this.form.action, this.form.serialize() + '&isAjax=1', function(data){
			if (data.result == "ok"){
				/* reset table cell back to normal */
				jQuery(data.elem).css("background-color", "cdfbb5");
			}
		}, json);
	}
	);
} /* end function */
jQuery(document).ready(init);
</script>
</head>
<body>
<div class="logout">
	<a href="{$_SERVER['PHP_SELF']}?logout">Log out</a>
</div>
$message
<table>
	<thead>
    <tr>
        <th width="130">Datum</td>
        <th width="180">Thuis</td>
        <th width="180">Uit</td>
        <th width="300">Aanwezig</td>
	</tr>
	</thead>
	<tbody>
HTML;

	//Query opstellen om gegevens uit de database te halen.
	$sql = "SELECT w.* a.aanwezig FROM wedstrijden w join aanwezigheid a on (w.wedstrijdid = a.wedstrijdid) where speler=%s";
	$query = sprintf($sql, dbReady($_SESSION['userData']['user']));
	$result = mysql_query($query) or mysql_bail(mysql_error(), $query);
	//rij maken zodat je gegevens kan gebruiken
	while($rij = mysql_fetch_assoc($result)){
	    array_map('htmlspecialchars', $rij);
		//set initial state
		if ($rij['aanwezig'] == 'aanwezig'){
			$_aanwezig = 'checked="checked"';
			$_afwezig = '';
		} else {
			$_afwezig = 'checked="checked"';
			$_aanwezig = '';
		}
	    echo <<<HTML
			<tr>
				<td width="130">{$rij['datum']}</td>
				<td width="180">{$rij['thuis']}</td>
				<td width="180">{$rij['uit']}</td>
				<td width="300" id="d_{$rij['wedstrijdid']}">
					<form action="{$_SERVER['PHP_SELF']}" method="POST" name="{$rij['wedstrijdid']}">
						<input type="hidden" name="gameID" value="{$rij['wedstrijdid']}" />
						<input type="hidden" name="action" value="updateGame" />
						<input type="radio" name="aanwezig" value="aanwezig" $_aanwezig />&nbsp;Aanwezig
						<input type="radio" name="aanwezig" value="afwezig" $_afwezig/>&nbsp;Afwezig
					</form>
				</td>
			</tr>
HTML;
	}	//end while
		echo <<<HTML
		
			</tbody>
		</table>
		</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']['spelerid']);
		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 where spelerid = %s and wedstrijdid=%s";
	$params = array($present, $player, $gameID);
	arary_map('dbReady', $params);
	$query = vpsrintf($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 (is_ajax()){
			echo json_encode(array('result'=>$result, 'elem', 'd_' . $_POST['wedstrijdid']));
			exit;
		} else {
			displayGameGrid($result);
		}
	break;
	case 'inclJQuery':
		$c = 0;
		while (!file_exists('jQuery.js')){
			if ($c > 10){
				echo '';
				exit;
			}
			cachejQuery();
			$c++;
		}
		readfile ('jQuery.js');
		break;
	default:
		displayGameGrid();
}
?>
 
First of all thank you for this long post and the code.
I just read through your comments and the code. I don't understand all of it and would be able to write even less, but I will try to learn from it. Being an analyst/tester will most likely mean I won't get this good, but I'll most likely learn to understand the code. I can try to build from that.

Again, thanks a lot. I'll try the scripts in an hour or so.

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

Window to my world
 
I get this error and am not sure what to make of it:

Notice: Undefined index: name in /var/ on line 171

I also noticed you didn't add this line:

require_once 'path/to/login.php';

I guess that's because you prefer a .htaccess file. Should I add it if I want to use it here?

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

Window to my world
 
The error most likely relates to your database schema. Post the schema in this thread.
 
As I'm not at home, from the top of my head:

Table spelers:
idspeler smallint (primary key)
user char
naam char
wachtwoord char
lastLoginTime int

Table wedstrijden:
idwedstrijd smallint (primary key)
datum date
thuis char
uit char

Table aanwezigheid:
spelerid smallint (primary key)
wedstrijdid smallint (primary key)
aanwezig char

I didn't know if ['name'] was a columnname from a table or something you coded. Else I wouldn't have bothered you.

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

Window to my world
 
perhaps you could post the full schema when you are next at the right terminal.
 
I checked and here's the structure. I don't know if it'll help, but I'll translate the fields.

Table spelers:
idspeler smallint (primary key) [ID player]
user char
naam char [name]
wachtwoord char [password]
lastLoginTime int

Table wedstrijden:
idwedstrijd smallint (primary key) [id game]
datum date [date]
thuis char [home team]
uit char [away team]

Table aanwezigheid:
spelerid smallint (foreign key) [player id]
wedstrijdid smallint (foreign key) [game id]
aanwezig char [attending]

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

Window to my world
 
Code:
<?php
//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

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 =                     '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 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(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();
	}
	if (logInExpired()){
		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 user=%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));
	array_map('dbReady', $params);
	$query = vpsrintf($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 "'$data'";	
}

/**
 * function to handle logouts
 * @return 
 */
function logout(){
	$_SESSION['isLoggedIn'] = false;
	unset($_SESSION['userData']);
	displayLoginForm('You have been logged out');
}

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>
	<title>An XHTML 1.0 Strict standard template</title>
	<meta http-equiv="content-type" 
		content="text/html;charset=utf-8" />
	<meta http-equiv="Content-Style-Type" content="text/css" />
</head>

<head>
<title>Game Presence Indicator</title>
<meta 	http-equiv="content-type" 
		content="text/html;charset=utf-8" />
<script type="text/javascript" src="{$_SERVER['PHP_SELF']}?action=inclJQuery"></script>
<script type="text/javascript">
function init(){
	/* set all the form cells to green to show clean */
	jQuery("td.frm").css('background-color', '#cdfbb5');

	jQuery("form input:radio").bind('click', function(e){
		e.preventDefault(); /* should not be necessary */
		e.stopPropagation();
		/* set table cell to red to show that it is dirty */
		jQuery(this).closest('td').css("background-color", '#f8c4a9');
		jQuery.post(this.form.action, this.form.serialize() + '&isAjax=1', function(data){
			if (data.result == "ok"){
				/* reset table cell back to normal */
				jQuery(data.elem).css("background-color", "cdfbb5");
			}
		}, json);
	}
	);
} /* end function */
jQuery(document).ready(init);
</script>
</head>
<body>
<div class="logout">
	<a href="{$_SERVER['PHP_SELF']}?logout">Log out</a>
</div>
$message
<table>
	<thead>
    <tr>
        <th width="130">Datum</td>
        <th width="180">Thuis</td>
        <th width="180">Uit</td>
        <th width="300">Aanwezig</td>
	</tr>
	</thead>
	<tbody>
HTML;

	//Query opstellen om gegevens uit de database te halen.
	$sql = "SELECT w.*, a.aanwezig as present FROM wedstrijden w join aanwezigheid a on (w.wedstrijdid = a.wedstrijdid) where 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
	while($rij = mysql_fetch_assoc($result)){
	    array_map('htmlspecialchars', $rij);
		//set initial state
		if ($rij['present'] == 'aanwezig'){
			$_aanwezig = 'checked="checked"';
			$_afwezig = '';
		} else {
			$_afwezig = 'checked="checked"';
			$_aanwezig = '';
		}
	    echo <<<HTML
			<tr>
				<td width="130">{$rij['datum']}</td>
				<td width="180">{$rij['thuis']}</td>
				<td width="180">{$rij['uit']}</td>
				<td width="300" id="d_{$rij['idwedstrijd']}">
					<form action="{$_SERVER['PHP_SELF']}" method="POST" name="{$rij['idwedstrijd']}">
						<input type="hidden" name="gameID" value="{$rij['idwedstrijd']}" />
						<input type="hidden" name="action" value="updateGame" />
						<input type="radio" name="aanwezig" value="aanwezig" $_aanwezig />&nbsp;Aanwezig
						<input type="radio" name="aanwezig" value="afwezig" $_afwezig/>&nbsp;Afwezig
					</form>
				</td>
			</tr>
HTML;
	}	//end while
		echo <<<HTML
		
			</tbody>
		</table>
		</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 aanwezig=%s where spelerid=%s and wedstrijdid=%s";
	$params = array($present, $player, $gameID);
	arary_map('dbReady', $params);
	$query = vpsrintf($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 (is_ajax()){
			echo json_encode(array('result'=>$result, 'elem', 'd_' . $_POST['wedstrijdid']));
			exit;
		} else {
			displayGameGrid($result);
		}
	break;
	case 'inclJQuery':
		$c = 0;
		while (!file_exists('jQuery.js')){
			if ($c > 10){
				echo '';
				exit;
			}
			cachejQuery();
			$c++;
		}
		readfile ('jQuery.js');
		break;
	default:
		displayGameGrid();
}
?>
 
Thanks. This works great.
Still I cannot update the table though. I get the radiobuttons in the gamePresence form, but there's no send button. Am I missing something?

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

Window to my world
 
assuming everything works, simply by changing the radio button (clicking) the database will be updated.

if it is not working then use firefox + firebug to find the error and report back in this thread.
 
XML tag name mismatch (expected br)
[Break on this error] </form>gamePres...nclJQuery (line 9)
jQuery is not defined
gamePresence.php()gamePresence.php (line 36)
[Break on this error] jQuery(document).ready(init);\ngamePresence.php (line 36

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

Window to my world
 
that's curious.

i will have to recreate the environment to debug.

please provide the full table schemas (in create format) with some sample data.
 
I noticed I'd made a mistake with the last field in the table 'aanwezigheid'. I already changed that in the code. Here's an extract for 1 player and a few matches from the database.

Table: spelers
Fields:
idspeler naam wachtwoord user lastLoginTime
Data:
2 Peter xxxx user1 1251474163

Table: wedstrijden
Fields:
idwedstrijd datum thuis uit
Data:
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

Table: aanwezigheid
Fields:
spelerid wedstrijdid aanwezigheid
Data:
2 1 aanwezig
2 2 aanwezig
2 3 aanwezig
2 4 aanwezig
2 5 afwezig

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

Window to my world
 
sorry but that data is not helpful. it should be in the form

Code:
create table if not exists tablename (tabledefs);
insert into tablename (data)

typically the easiest way to get this is to use phpmyadmin's export function but if you have root access it is just as easy to use the command line.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top