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
Ijekic
Forum Newbie
Posts: 11 Joined: Sat Aug 16, 2008 11:36 am
Location: Belgrade, Serbia
Post
by Ijekic » Wed Oct 15, 2008 1:32 pm
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!
requinix
Spammer :|
Posts: 6617 Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA
Post
by requinix » Wed Oct 15, 2008 2:57 pm
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.
Last edited by
requinix on Wed Oct 15, 2008 3:37 pm, edited 1 time in total.
onion2k
Jedi Mod
Posts: 5263 Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com
Post
by onion2k » Wed Oct 15, 2008 3:14 pm
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.
requinix
Spammer :|
Posts: 6617 Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA
Post
by requinix » Wed Oct 15, 2008 3:39 pm
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.
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
Thanks.
Ijekic
Forum Newbie
Posts: 11 Joined: Sat Aug 16, 2008 11:36 am
Location: Belgrade, Serbia
Post
by Ijekic » Thu Oct 16, 2008 5:43 am
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.
Onion thanks for pointing out that security issue.