Page 1 of 1

Assistance/optimization for a very simple code

Posted: Wed Oct 15, 2008 1:32 pm
by Ijekic
I guess it's rather simple question, but I'm stuck.

Is it possible to make this code (and codes like these) simpler? This looks to me unnecessary repetitive.

Code: Select all

 
$clname = array('about', 'portfolio', 'links', 'web', 'photo')
$fetchmsg = @mysql_fetch_object($dbselect) or die();
 
if ( $_GET["p"] == $clname[0] ) { $vardump = $fetchmsg->about; }
if ( $_GET["p"] == $clname[1] ) { $vardump = $fetchmsg->portfolio; }
if ( $_GET["p"] == $clname[2] ) { $vardump = $fetchmsg->links; }
if ( $_GET["p"] == $clname[3] ) { $vardump = $fetchmsg->web; }
if ( $_GET["p"] == $clname[4] ) { $vardump = $fetchmsg->photo; }
 
Thanks!

Re: Assistance/optimization for a very simple code

Posted: Wed Oct 15, 2008 2:57 pm
by requinix

Code: Select all

$clname = array("about", "portfolio", "links", "web", "photo");
$fetchmsg = @mysql_fetch_assoc($dbselect) or die();
if (isset($_GET["p"], $fetchmsg[$_GET["p"]]) && in_array($_GET["p"], $clname)) $vardump = $fetchmsg[$_GET["p"]];
Works because the $_GET[p] is also the name of the field in the table.

Re: Assistance/optimization for a very simple code

Posted: Wed Oct 15, 2008 3:14 pm
by onion2k
tasairis wrote:

Code: Select all

$clname = array("about", "portfolio", "links", "web", "photo");
$fetchmsg = @mysql_fetch_assoc($dbselect) or die();
if (isset($_GET["p"], $fetchmsg[$_GET["p"]])) $vardump = $fetchmsg[$_GET["p"]];
Works because the $_GET[p] is also the name of the field in the table.
What happens in your solution if I set $_GET['p'] to a value that is in $fetchmsg but isn't in $clname? Oops. :wink:

Re: Assistance/optimization for a very simple code

Posted: Wed Oct 15, 2008 3:39 pm
by requinix
onion2k wrote:What happens in your solution if I set $_GET['p'] to a value that is in $fetchmsg but isn't in $clname? Oops. :wink:
Oops indeed. I was going to use array_search, but then changed my mind in favor of in_array... except I forgot to put it in :banghead: Thanks.

Re: Assistance/optimization for a very simple code

Posted: Thu Oct 16, 2008 5:43 am
by Ijekic
Wow, thanks! I knew there was some logical and more elegant solution, but I was stuck. I tried using "foreach", but all I got was a mess. :crazy:

Onion thanks for pointing out that security issue.