Page 1 of 1

Code works, but I need some expert suggestions

Posted: Sun Sep 17, 2006 9:31 am
by pgolovko
There're over hundred of settings stored in database, and I dont want this function to be few pages long. Would there be a shorter, and more logical way to write this function?

Code: Select all

function cfg($v){
	$query = "SELECT * FROM `config` LIMIT 1";
	$result = mysql_query($query);
	echo mysql_error();
	if (mysql_num_rows($result) <> '') {
		while ($cfg = mysql_fetch_array($result)) {
			switch ($v) {
				case version:
					print $cfg['version'];
				break;
				case title:
					print $cfg['title'];
				break;
				case admin:
					print $cfg['admin'];
				break;
				case email:
					print $cfg['email'];
				break;
				}
			}
		}
	return $v;
	}
Here's an example of how I call it from my other pages:

Code: Select all

?>
<hr>
<?cfg("title");?> v.<?cfg("version");?>. by <?cfg("admin");?>, email: <?cfg("email");?>.
<hr>
<?
Thanks in advance!

Posted: Sun Sep 17, 2006 9:36 am
by feyd
Your code would suggest that the table has a column for each setting. Why was this route chosen?

Posted: Sun Sep 17, 2006 9:37 am
by pgolovko
Different settings on different rows.

Posted: Sun Sep 17, 2006 11:01 am
by onion2k
I'd go one of two routes. Either change the SQL in the function to only fetch the config variable with the requested name (eg "select * from config where name = '$v'") .. or if the variables are used on every page I'd put the all into an array at the beginning of each script and then just echo $config['title'] or $config['version'] etc where necessary. It depends on the rest of your code really.

Posted: Mon Sep 18, 2006 1:16 am
by pgolovko
Thanks guys, here's the updated function:

Code: Select all

function cfg($v){
	$query = "SELECT `$v` FROM `config` LIMIT 1";
	$result = mysql_query($query);
	echo mysql_error();
	if (mysql_num_rows($result) <> '') {
		while ($cfg = mysql_fetch_array($result)) {
			print $cfg['0'];
			}
		}
	return $v;
	}
?>

Posted: Mon Sep 18, 2006 1:52 am
by aaronhall
It might be better to load all of the config settings into a single array at the beginning of the page instead of calling a query every time you need to load a single config setting.