Jump to content

Is there a better way to do this?


ChrisMartino

Recommended Posts

Hello, Thanks for taking the time to read this.

 

I am creating a game server hosting company, And i need help making the function to create a new server in the database.

 

This is the format of the 'GameServers' Table:

 

ServerID	Owner	Game	Slots 	Expire	Directory	Executable	Port	DatePurchased	OnServer

 

Tables Explained

 

ServerID - Auto increment, I don't need to touch that.

 

Owner - This is the account that owns the server (The client's username who bought the server).

 

Game - This is the Game that the gameserver is for e.g IV:Multiplayer.

 

Expire -  This is the date in witch the server will expire.

 

Directory - This is the folder location on the dedicated server for the game server.

 

Executable - This is the name of the Executable for the server, Each one is unique so i can just run commands to kill the process's instead of storing PID's.

 

DatePurchased - the date the server was purchased.

 

OnServer - This is the Dedicated Server in witch the game server is on, The name of them are stored in a different table.

 

Function Explained.

 

CreateNewGameServer($game, $slots, $days, $owner, $server)

 

$game - The Multiplayer game that the client want's the server for.

$slots - The amount of max players the client has ordered.

$days - Days until the server expires.

$owner - The username of the owner of the server.

$server - The name of the Dedicated Server that the gameserver will be placed on. (Stored in a different database with root login information etc).

 

 

 

Help General

 

Can anyone help me fix a better create new server function, Because i feel that the current one i have made is far to unreliable at the moment, And some time's it doesn't even work and i am having to do queries twice to do certain things like to get the port from the last added record to the database so i can add +1 to the pervious port so the second server has a different port to the other ones, And also so i can get the ServerID from auto increment after it has been added to the database so i can make the excitable name etc, But i feel that this is unreliable, And it doesn't always work the way i hoped it would, I hope you can help with my problem, Here is the function to create a new server:

 

function CreateNewGameServer($game, $slots, $days, $owner, $server)
{
$CleanGame = mysql_real_escape_string($game);
$CleanSlots = mysql_real_escape_string($slots);
$CleanDays = mysql_real_escape_string($days);
$CleanOwner = mysql_real_escape_string($owner);
$CleanServer = mysql_real_escape_string($server);

$FindServer = mysql_query("SELECT * FROM Servers WHERE ServerName = '".$CleanServer."'");

if(mysql_num_rows($FindServer) == 1)
{
	// Check the the clients on the box are under 20
	if(GetClientsOnServer($CleanServer) > 20)
	{
		echo"<p>Error, The specified server is currently full.</p>";
	}
	else
	{
		$ExpireDate = mktime(0, 0, 0,  date("d")+$days, date("m"), date("Y"));
		$DatePurchased = date("d/m/y");

		mysql_query("INSERT INTO GameServers (Owner, Game, Slots, Expire, OnServer, DatePurchased) VALUES('".$CleanOwner."', '".$CleanGame."', '".$CleanSlots."', '".$ExpireDate."', '".$CleanServer."', '".$DatePurchased."')");

		$FindClient = mysql_query("SELECT * FROM GameServers WHERE Owner = '".$CleanOwner."' AND Expire  = '".$ExpireDate."' AND Game = '".$CleanGame."' AND OnServer = '".$CleanServer."'");

		$FindPort = mysql_query("SELECT * FROM `GameServers` ORDER BY `GameServers`.`ServerID`  DESC LIMIT 1");
		$PortLocate = mysql_fetch_array($FindPort);

		$FetchClient = mysql_fetch_array($FindClient);

		$ExeFile = "server$FetchClient[serverID]";
		$FileLocation = "/home/server$FetchClient[serverID]";
		$Port = $PortLocate['Port'] + 1;
		echo $PortLocate['Port'];

		mysql_query("UPDATE  `chrismar_xhost`.`GameServers` SET  `Executable` =  '".$ExeFile."' WHERE  `GameServers`.`ServerID` = '".$FetchClient[serverID]."' LIMIT 1 ");
		mysql_query("UPDATE  `chrismar_xhost`.`GameServers` SET  `Directory` =  '".$FileLocation."' WHERE  `GameServers`.`ServerID` = '".$FetchClient[serverID]."' LIMIT 1 ");
		mysql_query("UPDATE  `chrismar_xhost`.`GameServers` SET  `Port` =  '".$Port."' WHERE  `GameServers`.`ServerID` = '".$FetchClient[serverID]."' LIMIT 1 ");

	}	

}
else
{
	echo"<p>Invalid server specified.</p>";
}
}

 

Current Bugs with it

  • Doesn't always add the fields 'Directory' and 'Executable'
  • Doesn't add +1 to the last added record in the database for the port, Instead just adding 1 to nothing.
  • The date for the server to expire is weird and broken, For example today when i ran the function with the value of $days being '60' it put in the database: '1380862800'.

 

An example output of the function:

ServerID   	Owner	        Game	Slots 	Expire	                  Directory	        Executable	Port	        DatePurchased	OnServer
28	        Christopher	IV-MP	20	        1380862800	       /home/server28	server28	           1	             16/04/10	           alpha

 

 

Thanks for your time in reading this, I hope you can help with my situation, I know there are some intelligent people on these forums that could figure this out a more efficient way.

 

Thanks for any replies in advance :]

 

Chris.

 

 

 

 

Link to comment
Share on other sites

Suddenly found a soft spot for this ancient code :P.

 

here,

 

<?php

function CreateNewGameServer($game, $slots, $days, $owner, $server)
{
$CleanGame = mysql_real_escape_string($game);
$CleanSlots = mysql_real_escape_string($slots);
$CleanDays = mysql_real_escape_string($days);
$CleanOwner = mysql_real_escape_string($owner);
$CleanServer = mysql_real_escape_string($server);

$FindServer = mysql_query("SELECT * FROM Servers WHERE ServerName = '".$CleanServer."'");

if(mysql_num_rows($FindServer) == 1)
{
	// Grammer 
	// Check that the clients on the box are under 20
	if(GetClientsOnServer($CleanServer) > 20)
	{
		echo"<p>Error, The specified server is currently full.</p>";
	}
	else
	{
		// Timestamps please
		$ExpireDate = time()+($CleanDays * 86400); // Add nummber of days to timestamp.
		$DatePurchased = time(); // Much cleaner 

		// Guess you make the server entry now.
		$result = mysql_query("INSERT INTO GameServers (Owner, Game, Slots, Expire, OnServer, DatePurchased) VALUES('".$CleanOwner."', '".$CleanGame."', '".$CleanSlots."', '".$ExpireDate."', '".$CleanServer."', '".$DatePurchased."')");
		$ServerID = mysql_insert_id($result); // Set the new ID that was generated.

		// Find New Port
		$FindPort = mysql_query("SELECT Port FROM `GameServers` ORDER BY `GameServers`.`ServerID`"); // Ascending, no limit

		// Find use an unsused port
		$Port = 0;
		while($row = mysql_fetch_assoc($FindPort)){ // Keep going for every row

			// If Port is 0, set it to the current port number. Otherwise keep it the same.
			$Port = ($Port == 0)? $row['Port'] : $Port;

			// If The port numbers dont match, we got a new one..
			if($row['Port'] !== $Port){
				Break; // Break out of the loop, $Port will contain the current unused port number.
			}

			// Increment port, so we can check if the next number is taken in the next loop.
			$Port++;
		}
		// One, Single, Epic (well not so much) Query.
		$Result = mysql_query("UPDATE  `chrismar_xhost`.`GameServers` 
			SET  `Executable` =  'server".$ServerID."',
				`Directory` =  '/home/server".$ServerID."',
				`Port` =  '".$Port."',
			WHERE  `GameServers`.`ServerID` = '".$ServerID."' LIMIT 1 ");

		echo($Port);
	}	

}
else
{
	echo"<p>Invalid server specified.</p>";
}
}

?>

 

Use timestamps for dates, much easier.

 

Also with the new method for finding an unused port, you can freely delete any record, and using this function will fill in any port gaps.

 

-cb-

Link to comment
Share on other sites

Try this:

	
$ExeFile = "server$FetchClient['ServerID']";
$FileLocation = "/home/server$FetchClient['ServerID']";
$Port = $PortLocate['Port']+=1;
echo $PortLocate['Port'];

mysql_query("UPDATE  `chrismar_xhost`.`GameServers` SET  `Executable` =  '".$ExeFile."' WHERE  `GameServers`.`ServerID` = '".$FetchClient['ServerID']."' LIMIT 1 ");
mysql_query("UPDATE  `chrismar_xhost`.`GameServers` SET  `Directory` =  '".$FileLocation."' WHERE  `GameServers`.`ServerID` = '".$FetchClient['ServerID']."' LIMIT 1 ");
mysql_query("UPDATE  `chrismar_xhost`.`GameServers` SET  `Port` =  '".$Port."' WHERE  `GameServers`.`ServerID` = '".$FetchClient['ServerID']."' LIMIT 1 ");

Link to comment
Share on other sites

Sorry about that, dont really know what happened there.

 

$FindServer = mysql_query("SELECT * FROM Servers WHERE ServerName = '".$CleanServer."'") or die(mysql_error());

 

Use this and tell u what it says, it should show an error message from mysql.

 

-cb-

 

The error wasn't anything to do with that :S, I was getting the error from the code you gave me, I'm using the function you gave me but it keeps giving me this error:

 

Warning: mysql_insert_id(): supplied argument is not a valid MySQL-Link resource in /home3/chrismar/public_html/x-host.co.uk/api/gameserver_api.php on line 108

 

Line 108 is:

 

$ServerID = mysql_insert_id($result); // Set the new ID that was generated.

 

Link to comment
Share on other sites

Oops sorry bout that, read mysql query for some reason lol.

 

Anyway try this, see what it says, im guessing some type mismatch;

 

$result = mysql_query("INSERT INTO GameServers (Owner, Game, Slots, Expire, OnServer, DatePurchased) VALUES('".$CleanOwner."', '".$CleanGame."', '".$CleanSlots."', '".$ExpireDate."', '".$CleanServer."', '".$DatePurchased."')") or die(mysql_error());

 

-cb-

Link to comment
Share on other sites

Oooo my bad, link-resource is the connection handler i would imagine;

 

but it's not needed, use the original code i posted with a minor midification;

 

$ServerID = mysql_insert_id(); // remove $result

 

That code was custom made for you :P. just that one glitch (hopefully).

 

-cb-

Link to comment
Share on other sites

Hmm, Suspicsious;

 

<?php

function CreateNewGameServer($game, $slots, $days, $owner, $server)
{
$CleanGame = mysql_real_escape_string($game);
$CleanSlots = mysql_real_escape_string($slots);
$CleanDays = mysql_real_escape_string($days);
$CleanOwner = mysql_real_escape_string($owner);
$CleanServer = mysql_real_escape_string($server);

$FindServer = mysql_query("SELECT * FROM Servers WHERE ServerName = '".$CleanServer."'");

if(mysql_num_rows($FindServer) == 1)
{
	// Grammer 
	// Check that the clients on the box are under 20
	if(GetClientsOnServer($CleanServer) > 20)
	{
		echo"<p>Error, The specified server is currently full.</p>";
	}
	else
	{
		// Timestamps please
		$ExpireDate = time()+($CleanDays * 86400); // Add nummber of days to timestamp.
		$DatePurchased = time(); // Much cleaner 

		// Guess you make the server entry now.
		$result = mysql_query("INSERT INTO GameServers (Owner, Game, Slots, Expire, OnServer, DatePurchased) VALUES('".$CleanOwner."', '".$CleanGame."', '".$CleanSlots."', '".$ExpireDate."', '".$CleanServer."', '".$DatePurchased."')");
		$ServerID = mysql_insert_id(); // Set the new ID that was generated.

		// Find New Port
		$FindPort = mysql_query("SELECT Port FROM `GameServers` ORDER BY `GameServers`.`ServerID`"); // Ascending, no limit

		// Find use an unsused port
		$Port = 0;
		while($row = mysql_fetch_assoc($FindPort)){ // Keep going for every row

			// If Port is 0, set it to the current port number. Otherwise keep it the same.
			$Port = ($Port == 0)? $row['Port'] : $Port;

			// If The port numbers dont match, we got a new one..
			if($row['Port'] !== $Port){
				Break; // Break out of the loop, $Port will contain the current unused port number.
			}

			// Increment port, so we can check if the next number is taken in the next loop.
			$Port++;
		}
		// One, Single, Epic (well not so much) Query.
		$query = "UPDATE  `chrismar_xhost`.`GameServers` 
			SET  `Executable` =  'server".$ServerID."',
				`Directory` =  '/home/server".$ServerID."',
				`Port` =  '".$Port."',
			WHERE  `GameServers`.`ServerID` = '".$ServerID."' LIMIT 1 ";
		$Result = mysql_query($query) or die(mysql_error());

		echo("affected rows: ".mysql_affected_rows($Result)."<br/>".$query); // Check the query
	}	

}
else
{
	echo"<p>Invalid server specified.</p>";
}
}

?>

 

Try this and tell us what it says.

 

-cb-

Link to comment
Share on other sites

cool works!, now one problem though, The date's that are being put in the database are still this weird format:

 

1271479417

 

And the port doesn't add +1 each time it just stays the same :/

$Port = $PortLocate['Port']+=1;

 

Should fix the port problem, however, I'm rubbish with dates.

Link to comment
Share on other sites

cool works!, now one problem though, The date's that are being put in the database are still this weird format:

 

1271479417

 

And the port doesn't add +1 each time it just stays the same :/

$Port = $PortLocate['Port']+=1;

 

Should fix the port problem, however, I'm rubbish with dates.

 

Dude, Why are you keep posting that, It's totally irrelevant.

Link to comment
Share on other sites

Ok try this:

 

<?php

function CreateNewGameServer($game, $slots, $days, $owner, $server)
{
$CleanGame = mysql_real_escape_string($game);
$CleanSlots = mysql_real_escape_string($slots);
$CleanDays = mysql_real_escape_string($days);
$CleanOwner = mysql_real_escape_string($owner);
$CleanServer = mysql_real_escape_string($server);

$FindServer = mysql_query("SELECT * FROM Servers WHERE ServerName = '".$CleanServer."'");

if(mysql_num_rows($FindServer) == 1)
{
	// Grammer 
	// Check that the clients on the box are under 20
	if(GetClientsOnServer($CleanServer) > 20)
	{
		echo"<p>Error, The specified server is currently full.</p>";
	}
	else
	{
		// Timestamps please
		$ExpireDate = time()+($CleanDays * 86400); // Add nummber of days to timestamp.
		$DatePurchased = time(); // Much cleaner 

		// Guess you make the server entry now.
		$result = mysql_query("INSERT INTO GameServers (Owner, Game, Slots, Expire, OnServer, DatePurchased) VALUES('".$CleanOwner."', '".$CleanGame."', '".$CleanSlots."', '".$ExpireDate."', '".$CleanServer."', '".$DatePurchased."')");
		$ServerID = mysql_insert_id(); // Set the new ID that was generated.

		// Find New Port
		$FindPort = mysql_query("SELECT Port FROM `GameServers` ORDER BY `GameServers`.`Port`") or die(mysql_error()); // Ascending, no limit

		// Find use an unsused port
		$Port = 0;
		while($row = mysql_fetch_assoc($FindPort)){ // Keep going for every row

			// If Port is 0, set it to the current port number. Otherwise keep it the same.
			$Port = ($Port == 0)? $row['Port'] : $Port;

			// DEBUG
			echo("Port: ".$Port."<Br />");

			// If The port numbers dont match, we got a new one..
			if($row['Port'] !== $Port){
				Break; // Break out of the loop, $Port will contain the current unused port number.
			}

			// Increment port, so we can check if the next number is taken in the next loop.
			$Port++;
		}
		// One, Single, Epic (well not so much) Query.
		$query = "UPDATE  `chrismar_xhost`.`GameServers` 
			SET  `Executable` =  'server".$ServerID."',
				`Directory` =  '/home/server".$ServerID."',
				`Port` =  '".$Port."'
			WHERE  `GameServers`.`ServerID` = '".$ServerID."' LIMIT 1 ";
		$Result = mysql_query($query) or die(mysql_error());

		echo("affected rows: ".mysql_affected_rows($Result)."<br/>".$query); // Check the query
	}	

}
else
{
	echo"<p>Invalid server specified.</p>";
}
}

?>

 

It should shed light on the port number problem.

 

That wierd format is called a UNIX Timestamp. Its the number of seconds since the unix epoch, January 1st 1970 summat. But its a very useful way of comparing dates in a numerical way. Also, you can format it in anyway using the date() function as normal, but passing the timestamp as the second argument:

$timestamp = time();
echo(date("d/m/Y h:i:s",$timetamp);

 

-cb-

Link to comment
Share on other sites

The idea was to simplify. I would suggest to let MySQL do some of the heavy lifting. Using native MySQL functions NOW(), MAX(), IF(), and ISNULL(), it can take care of the timestamps and finding a new port number.

 

It's hard to rewrite this without being able to run it, but take a look at this:

 

<?php

function CreateNewGameServer($game, $slots, $days, $owner, $server)
{
$CleanGame		= mysql_real_escape_string($game);
$CleanSlots		= mysql_real_escape_string($slots);
$CleanDays		= mysql_real_escape_string($days);
$CleanOwner		= mysql_real_escape_string($owner);
$CleanServer	= mysql_real_escape_string($server);

$FindServer = mysql_query("SELECT * FROM Servers WHERE ServerName = '".$CleanServer."'");

if (mysql_num_rows($FindServer) == 1) {

	// Check that the clients on the box are under 20
	if (GetClientsOnServer($CleanServer) >= 20) {

		echo"<p>Error, The specified server is currently full.</p>";

	} else {

		// create server entry
		$result = mysql_query("INSERT INTO GameServers (Owner, Game, Slots, Expire, OnServer, DatePurchased) VALUES('".$CleanOwner."', '".$CleanGame."', '".$CleanSlots."', DATE_ADD(NOW, INTERVAL '.$CleanDays.' DAYS), '".$CleanServer."', NOW())");

		// get the new ID that was generated.
		$ServerID = mysql_insert_id();

		// find highest existing port + 1; default port 30000 if none yet exists
		$FindPort = mysql_query("SELECT IF(ISNULL(MAX(Port)), 30000, MAX(Port) + 1) newPort FROM `GameServers`");
		$Port = mysql_result($FindPort, 0);

		// update new server 
		$Result = mysql_query("UPDATE  `chrismar_xhost`.`GameServers` 
								SET  `Executable` =  'server".$ServerID."',
									`Directory` =  '/home/server".$ServerID."',
									`Port` =  '".$Port."'
								WHERE  `GameServers`.`ServerID` = '".$ServerID."' LIMIT 1 ");

		echo($Port);
	}

} else {
	echo"<p>Invalid server specified.</p>";
}
}

?>

 

I wasn't totally clear on how you determine a port number. Can different servers have the same port number or is it globabally unique? The way I coded it above, it finds a globally unique port number and starts with a default of 30000 if none if given in the GameServers table.

Link to comment
Share on other sites

Ok try this:

 

<?php

function CreateNewGameServer($game, $slots, $days, $owner, $server)
{
$CleanGame = mysql_real_escape_string($game);
$CleanSlots = mysql_real_escape_string($slots);
$CleanDays = mysql_real_escape_string($days);
$CleanOwner = mysql_real_escape_string($owner);
$CleanServer = mysql_real_escape_string($server);

$FindServer = mysql_query("SELECT * FROM Servers WHERE ServerName = '".$CleanServer."'");

if(mysql_num_rows($FindServer) == 1)
{
	// Grammer 
	// Check that the clients on the box are under 20
	if(GetClientsOnServer($CleanServer) > 20)
	{
		echo"<p>Error, The specified server is currently full.</p>";
	}
	else
	{
		// Timestamps please
		$ExpireDate = time()+($CleanDays * 86400); // Add nummber of days to timestamp.
		$DatePurchased = time(); // Much cleaner 

		// Guess you make the server entry now.
		$result = mysql_query("INSERT INTO GameServers (Owner, Game, Slots, Expire, OnServer, DatePurchased) VALUES('".$CleanOwner."', '".$CleanGame."', '".$CleanSlots."', '".$ExpireDate."', '".$CleanServer."', '".$DatePurchased."')");
		$ServerID = mysql_insert_id(); // Set the new ID that was generated.

		// Find New Port
		$FindPort = mysql_query("SELECT Port FROM `GameServers` ORDER BY `GameServers`.`Port`") or die(mysql_error()); // Ascending, no limit

		// Find use an unsused port
		$Port = 0;
		while($row = mysql_fetch_assoc($FindPort)){ // Keep going for every row

			// If Port is 0, set it to the current port number. Otherwise keep it the same.
			$Port = ($Port == 0)? $row['Port'] : $Port;

			// DEBUG
			echo("Port: ".$Port."<Br />");

			// If The port numbers dont match, we got a new one..
			if($row['Port'] !== $Port){
				Break; // Break out of the loop, $Port will contain the current unused port number.
			}

			// Increment port, so we can check if the next number is taken in the next loop.
			$Port++;
		}
		// One, Single, Epic (well not so much) Query.
		$query = "UPDATE  `chrismar_xhost`.`GameServers` 
			SET  `Executable` =  'server".$ServerID."',
				`Directory` =  '/home/server".$ServerID."',
				`Port` =  '".$Port."'
			WHERE  `GameServers`.`ServerID` = '".$ServerID."' LIMIT 1 ";
		$Result = mysql_query($query) or die(mysql_error());

		echo("affected rows: ".mysql_affected_rows($Result)."<br/>".$query); // Check the query
	}	

}
else
{
	echo"<p>Invalid server specified.</p>";
}
}

?>

 

It should shed light on the port number problem.

 

That wierd format is called a UNIX Timestamp. Its the number of seconds since the unix epoch, January 1st 1970 summat. But its a very useful way of comparing dates in a numerical way. Also, you can format it in anyway using the date() function as normal, but passing the timestamp as the second argument:

$timestamp = time();
echo(date("d/m/Y h:i:s",$timetamp);

 

-cb-

 

 

Port:

Port: 1

 

Warning: mysql_affected_rows(): supplied argument is not a valid MySQL-Link resource in /home3/chrismar/public_html/x-host.co.uk/api/gameserver_api.php on line 139

affected rows:

UPDATE `chrismar_xhost`.`GameServers` SET `Executable` = 'server48', `Directory` = '/home/server48', `Port` = '1' WHERE `GameServers`.`ServerID` = '48' LIMIT 1

 

 

:/

Link to comment
Share on other sites

OK:

Ken2k7 - Your code isnt what were now disucussing, keep up with the thread...

dirkers - you have removed 2 key functionality - a very easy method of comparing times, and filling in any port gaps there may be.

Im ont want to sound picky, but try to keep focus..

 

Now, a couple questions, ad one thing to try,

 

Question 1: Does your first entry in your database have a port number of 1? if so why?

Question 2: Do you currently have any rows in your database? or do we have to insert a new one first?

 

Ok, ima get you to fix this one:

look at "not a valid MySQL-Link resource", what does it mean? _LINK_ Resource? hmm, like earlier??

FYI: "Supplied Argument" is the variable passed to this function (at the moment it is $Result. $Resultis a Result Resource, you need a LINK-resource.

 

-cb-

Link to comment
Share on other sites

OK:

Ken2k7 - Your code isnt what were now disucussing, keep up with the thread...

dirkers - you have removed 2 key functionality - a very easy method of comparing times, and filling in any port gaps there may be.

Im ont want to sound picky, but try to keep focus..

 

Now, a couple questions, ad one thing to try,

 

Question 1: Does your first entry in your database have a port number of 1? if so why?

Question 2: Do you currently have any rows in your database? or do we have to insert a new one first?

 

Ok, ima get you to fix this one:

look at "not a valid MySQL-Link resource", what does it mean? _LINK_ Resource? hmm, like earlier??

FYI: "Supplied Argument" is the variable passed to this function (at the moment it is $Result. $Resultis a Result Resource, you need a LINK-resource.

 

-cb-

 

Yea i have a entry in the database already with the port '9999' and a ServerID witch is auto increment

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.