Code works, but I need some expert suggestions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
pgolovko
Forum Commoner
Posts: 38
Joined: Sun Sep 17, 2006 9:13 am

Code works, but I need some expert suggestions

Post 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!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Your code would suggest that the table has a column for each setting. Why was this route chosen?
User avatar
pgolovko
Forum Commoner
Posts: 38
Joined: Sun Sep 17, 2006 9:13 am

Post by pgolovko »

Different settings on different rows.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post 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.
User avatar
pgolovko
Forum Commoner
Posts: 38
Joined: Sun Sep 17, 2006 9:13 am

Post 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;
	}
?>
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post 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.
Post Reply