<?php
#### read_pids reads recursively all pids of given project ###########
function read_pids( $pid, &$s ){
	if( !$sid = mysql_query( "select proj_id from metatext
		where ref_by = $pid and status = 'act'" )) {
		echo "Error No. 23-$pid: ".mysql_errno().": ".mysql_error();
		exit;
	}
	if( mysql_num_rows( $sid ) == 0 ) return 0;
	while( $row = mysql_fetch_array( $sid )){
		$pid = $row[ "proj_id" ];
		$s .= ", $pid";
		read_pids( $pid, $s );
	}
	return 1;
}

#### count_memb counts members of all sub-/projects ##################
function count_memb( $pid ){
	# build IN-clause for select-statement
	$s = "($pid";
	read_pids( $pid, $s );
	$s .= ')';
	if( !$nid = mysql_query( "select distinct memb_id from projmemb
		where proj_id in $s" )) {
		echo "Error No. 24: ".mysql_errno().": ".mysql_error();
		exit;
	}
	$num = mysql_num_rows( $nid );
	return $num;
}

#### update_member_num recursively updates membnum ###################
function update_member_num( $pid ){
	$s = "update metatext set membnum = ".count_memb( $pid );
	$s .= " where proj_id = $pid";
	if( !mysql_query( $s )) {
		echo "Error No. 25-$pid: ".mysql_errno().": ".mysql_error();
		exit;
	}
	if( !$id = mysql_query( "select ref_by from metatext
		where proj_id = $pid and status = 'act'" )) {
		echo "Error No. 26-$pid: ".mysql_errno().": ".mysql_error();
		exit;
	}
	if( mysql_num_rows( $id ) == 0 ) return 0;
	while( $row = mysql_fetch_array( $id )){
		$pid = $row[ "ref_by" ];
		if( $pid > 0 ) update_member_num( $pid );
	}
	return 1;
}
?>
