Switch not working

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
father
Forum Newbie
Posts: 5
Joined: Fri May 23, 2003 10:15 pm
Location: Australia

Switch not working

Post by father »

New to php!

Bought the PHP and MySQL web dev. book 2nd edition, seems like a good book but I can't get the following working.

Code in the html form:

Code: Select all

<tr>
 	<td>How did you find Bob's</td>
	<td><select name="find">
			<option value = "a">I'm a regular customer
			<option value = "b">TV advertising
			<option value = "c">Phone Directory
			<option value = "d">Word of mouth
		</select>
	</td>
 </tr>
Code in my PHP File:

Code: Select all

switch ($find)
 &#123;
 	case 'a':
		echo '<p>Regular Customer.</p>';
		break;
	case 'b':
		echo '<p>TV Add.</p>';
		break;		
	case 'c':
		echo '<p>Phone Directory.</p>';
		break;
	case 'd':
		echo '<p>Word of Mouth.</p>';
		break;
	default :
		echo '<p>Unknown.</p>';
		break;
 &#125;
WHenever I submit my form the result is always comes back wit the default "unknown"

I can't find whats wrong :?
evilcoder
Forum Contributor
Posts: 345
Joined: Tue Dec 17, 2002 5:37 am
Location: Sydney, Australia

Post by evilcoder »

ok, i know its not really what your asking but use if/else, much easier and looks better :)

Code: Select all

if ( $find == "a" ) 
&#123; 
     echo "<p>Regular Customer.</p>"; 
&#125;
elseif ( $find == "b" )
&#123;
     echo "<p>TV Add.</p>"; 
&#125;
elseif ( $find == "c" )
&#123;
     echo "<p>Phone Directory.</p>"; 
&#125;
elseif ( $find == "d" )
&#123;
     echo "<p>Word of Mouth.</p>"; 
&#125;
else
&#123;
     echo "<p>Unknown.</p>";
&#125;
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

This is just a wild guess but try replacing:

switch ($find)

..with..

switch ($_POST['find'])

.. and see the manual for info about register globals (I think you may have reg globs off which is good).

Personally I like switch for a simple list of possible values like that.

(oh and I'm assuming you've got the rest of the form defined OK - not posted)
father
Forum Newbie
Posts: 5
Joined: Fri May 23, 2003 10:15 pm
Location: Australia

Post by father »

Yeah forgot about that one, using that lengthy way to specify variables is a pain so I'm adding the following line to the top of my code

$find = $_REQUEST['find'];

That fixed it alright and I can still use the short $find in the code.

I have to say that I prefer switch over elseif, it makes the code more readable.

Thanks though guys!
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

Don't use quotes
Post Reply