Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Switch/case?? 1

Status
Not open for further replies.

VAMick

Programmer
Nov 18, 2005
64
US
I have a page that i'd like to load varying textarea boxes populated by an entry in the database. I'd like different boxes to show up based on the url string. for example...

...sitetext.php?page=Main would load 3 textarea boxes with the appropriate data.

if I selected sitetext.php?page=aboutus it would load a different layout.

etc etc.

now, would I use the switch/case function to echo the different layouts I want to see? Or would I use something else?

thanks.
 
you could use a switch/case function if you wanted but if you are nto sure how to do that then just use If/elsif statements eg..
Code:
if ($page=="Main"){
  blah;
}
elsif ($page == "aboutus"){

NB. I did not really test my code just off the top of my head without firing up any editior, so sorry if i confused some language semantics...
 
What if there were like 5 pages to pick from? would it be multiple IF's??

I have seen a switch/case done, but I didn't know how to select from the URL.
 
Definately learn the switch statement. It is much better on your processing time and much easier to follow.

Code:
$page = $_REQUEST['page'];
switch($page) {
    case "Links":
        print "This is Links.";
        break;
    case "aboutus":
       print "This is the about us page";
       break;
    case "Main":
    default:
        print "This is the Main/default section";
        break;
}


You can use as many different case statements as you want. Notice each one must end with break or else the next case is evaluated too. This is a good way to use default.. make sure you put your main last and leave out the break.. that way you don't have to type the same code for default (basically default: is the else section)



-Dustin
Rom 8:28
 
You can use the '$_GET' superglobal to ensure that your variable passed in your url is available in your php script VAMick.

Code:
$page = $_GET['page']











 
Just for clarification, Dweezel is correct. I used $_REQUEST which will grab the variable from $_GET or $_POST. There are different reasons to use different global vars.. mainly security. Just note, that if you use a form and its type is POST, you have to use $_REQUEST or $_POST.. $_GET will not be populated.

-Dustin
Rom 8:28
 
Ok, I've got the switch working on the page, but now I'm having a bit of a problem getting the textarea boxes to populate with data from the database depending on which "page" was selected.

I'll post a bit of the code, but basically, does an echo allow php code to be written inside the echo? See below..

Code:
<?php $page = $_REQUEST['page'];
          switch($page) {
          case "Main":
          echo '  
		  <form name="form1" method="post" action=""><tr class="font"><td bgcolor="#CCCCCC">Area: Top Main Box</td></tr>
	<tr>	  <td><p>
              <textarea name="area1" id="area1" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Right Column</td></tr>
	<tr>	  <td><p>
              <textarea name="area2" id="area2" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Lower 1st Box</td></tr>
	<tr>	  <td><p>
              <textarea name="area3" id="area3" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Lower 2nd Box</td></tr>
	<tr>	  <td><p>
              <textarea name="area4" id="area4" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Lower 3rd Box</td></tr>
	<tr>	  <td><p>
              <textarea name="area5" id="area5" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			<tr><td><p>
                <input name="Submit2" type="submit" id="Submit2" value="Submit">
                <input name="page" type="hidden" value="Main">
            </p></td></tr></form>
		  ';
          break;
          case "Aboutus":
          echo '  <form name="form1" method="post" action=""><tr class="font"><td bgcolor="#CCCCCC">Area: Top Main Box</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Right Column</td></tr>

Small snippet of code. now, i tried putting a <?php echo ....['fieldname'] ?> inside the first textarea box, so that if the page "Main" was selected it looked up that record in the db and would populate. I keep getting errors as if I am not allowed to put more php inside the echo. HELP!!!!
 
I think I understand what you're asking.. you actually just need to end the string, add your text, and then continue the sring. You can easily do this with the concatenation operator ('.')

Code:
echo '<tr class="font"><td bgcolor="#CCCCCC">Area: Right Column</td></tr>
    <tr>      <td><p>
              <textarea name="area2" id="area2" cols="95" rows="25">' . $row['fieldname'] . '</textarea>
            </p>
              </td></tr>';
break;

For more info see the manual page
-Dustin
Rom 8:28
 
YES. That's exactly what I was looking for, I just couldn't remember the exact syntax to use the .

 
Alright, this is really killing me. Tried to figure it out for myself over the last few hours, but I keep getting the error

You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near '=
How to Search

Here is the entire page so maybe someone can see where i'm going wrong. I know it has to do with the Switch/Case that I'm using, but I still don't know where the errant code is. Thanks for the assist.

Code:
<?php require_once('../Connections/spectrum.php'); ?>
<?php
mysql_select_db($database_spectrum, $spectrum);
$query_rs_sitetext = "SELECT * FROM spec_sitetext ";
$rs_sitetext = mysql_query($query_rs_sitetext, $spectrum) or die(mysql_error());
$row_rs_sitetext = mysql_fetch_assoc($rs_sitetext);
$totalRows_rs_sitetext = mysql_num_rows($rs_sitetext);

?>
		  <?php 
		  function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "mainadd")) {
 				 $updateSQL = sprintf("UPDATE spec_sitetext SET area1=%s, area2=%s, area3=%s, area4=%s, area5=%s  WHERE siteid=%s",
                       GetSQLValueString($_POST['area1'], "longtext"),
                       GetSQLValueString($_POST['area2'], "longtext"),
                       GetSQLValueString($_POST['area3'], "longtext"),
                       GetSQLValueString($_POST['area4'], "longtext"),
                       GetSQLValueString($_POST['area5'], "longtext"),
					   GetSQLValueString($_POST['siteid'], "int"));

  				mysql_select_db($database_spectrum, $spectrum);
  				$Result1 = mysql_query($updateSQL, $spectrum) or die(mysql_error());
				}
?>
<?php include_once "../mainfile.php"; //load the global vars and functions ?>
<html>
<head>
<title>Category Addition</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="../style.css" rel="stylesheet" type="text/css">
<script language="javascript" type="text/javascript" src="../tinymce/jscripts/tiny_mce/tiny_mce.js"></script>
<script language="javascript" type="text/javascript">
<!--


tinyMCE.init({
	safari_warning : false,
	mode : "textareas",
	theme : "advanced",
	plugins : "table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,zoom,flash,searchreplace,print,contextmenu",
	theme_advanced_buttons1_add_before : "save,separator",
	theme_advanced_buttons1_add : "fontselect,fontsizeselect",
	theme_advanced_buttons2_add : "separator,insertdate,inserttime,preview,zoom,separator,forecolor,backcolor",
	theme_advanced_buttons2_add_before: "cut,copy,paste,separator,search,replace,separator",
	theme_advanced_buttons3_add_before : "tablecontrols,separator",
	theme_advanced_buttons3_add : "emotions,iespell,flash,advhr,separator,print",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_path_location : "bottom",
	plugin_insertdate_dateFormat : "%Y-%m-%d",
	plugin_insertdate_timeFormat : "%H:%M:%S",
	extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
	external_link_list_url : "example_data/example_link_list.js",
	external_image_list_url : "example_data/example_image_list.js",
	flash_external_list_url : "example_data/example_flash_list.js"
});

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}
//-->
</script>

</head>
<body>
<?php adminToolbar("<b>Category Admin</b> - Please Enter New Categories"); ?>
<table width="800" border="0" align="center">
  <tr>
    <td colspan="2"><form action="" method="post" name="pageselect" id="pageselect">
      <select name="text menu" onChange="MM_jumpMenu('parent',this,0)">
        <option selected>Select a page</option>
        <option value="sitetext_test.php?page=Main">Main Page</option>
        <option value="sitetext_test.php?page=Aboutus">About Us</option>
        <option value="sitetext_test.php?page=Suppliers">Supplier</option>
        <option value="sitetext_test.php?page=Categories">Categories</option>
        </select>
            </form>    </td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>Insert page key image here... </td>
  </tr>
  <tr>
    <td height="61" colspan="2">
      <table width="800" align="center" class="dottedborder">
        <tr class="font">
          <td>Page: <?php $page = $_REQUEST['page'];
		  echo $page; ?> </td>
        </tr>
        <tr><?php $page = $_REQUEST['page'];
          switch($page) {
          case "Main":
		   
		  $colname_rs_page = "-1";
				if (isset($_GET['page'])) {
  				$colname_rs_page = (get_magic_quotes_gpc()) ? $_GET['page'] : addslashes($_GET['page']);
				}
				mysql_select_db($database_spectrum, $spectrum);
				$query_rs_page = sprintf("SELECT * FROM spec_sitetext WHERE page = '%s'", $colname_rs_page);
				$rs_page = mysql_query($query_rs_page, $spectrum) or die(mysql_error());
				$row_rs_page = mysql_fetch_assoc($rs_page);
				$totalRows_rs_page = mysql_num_rows($rs_page);
			mysql_free_result($rs_page);

     echo '  
		  <form name="mainadd" method="post" action=' .  "$editFormAction" . '><tr class="font"><td bgcolor="#CCCCCC">Area: Top Main Box</td></tr>
	<tr>	  <td><p>
              <textarea name="area1" id="area1" cols="95" rows="25">' . $row_rs_page['area1'] . '</textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Right Column</td></tr>
	<tr>	  <td><p>
              <textarea name="area5" id="area5" cols="95" rows="25">' . $row_rs_page['area5'] . '</textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Lower 1st Box</td></tr>
	<tr>	  <td><p>
              <textarea name="area2" id="area2" cols="95" rows="25">' . $row_rs_page['area2'] . '</textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Lower 2nd Box</td></tr>
	<tr>	  <td><p>
              <textarea name="area3" id="area3" cols="95" rows="25">' . $row_rs_page['area3'] . '</textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Lower 3rd Box</td></tr>
	<tr>	  <td><p>
              <textarea name="area4" id="area4" cols="95" rows="25">' . $row_rs_page['area4'] . '</textarea>
            </p>
              </td></tr>
			<tr><td><p>
				<input name="siteid" type="hidden" value="' . $row_rs_page['siteid'] . '">
                <input name="submit" type="submit" id="submit" value="Submit">
                <input name="MM_update" type="hidden" value="mainadd">
            </p></td></tr></form>
		  ';
          break;
          case "Aboutus":
          echo '  <form name="form1" method="post" action=""><tr class="font"><td bgcolor="#CCCCCC">Area: Top Main Box</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Right Column</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Lower 1st Box</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Lower 2nd Box</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Lower 3rd Box</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			<tr><td><p>
                <input name="Submit2" type="submit" id="Submit2" value="Submit">
                <input name="hiddenField" type="hidden" value="">
            </p></td></tr></form>
		  ';
          break;
          case "Suppliers":
		  echo '  <form name="form1" method="post" action=""><tr class="font"><td bgcolor="#CCCCCC">Area: Top Main Box</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Right Column</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Lower 1st Box</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Lower 2nd Box</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Lower 3rd Box</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			<tr><td><p>
                <input name="Submit2" type="submit" id="Submit2" value="Submit">
                <input name="hiddenField" type="hidden" value="">
            </p></td></tr></form>
		  ';
		  break;
		            case "Categories":
		  echo '  <form name="form1" method="post" action=""><tr class="font"><td bgcolor="#CCCCCC">Area: Top Main Box</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Right Column</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Lower 1st Box</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Lower 2nd Box</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			  <tr class="font"><td bgcolor="#CCCCCC">Area: Lower 3rd Box</td></tr>
	<tr>	  <td><p>
              <textarea name="sitetext" id="sitetext" cols="95" rows="25"></textarea>
            </p>
              </td></tr>
			<tr><td><p>
                <input name="Submit2" type="submit" id="Submit2" value="Submit">
                <input name="hiddenField" type="hidden" value="">
            </p></td></tr></form>
		  ';
		  break;
          default:
          print "This is the Main/default section";
          break;
          } 
		  
		  ?>
		  </tr>
        <tr class="font">
          
        </tr>
      </table>
    </td>
  </tr>
</table>
<p>&nbsp;</p>
</body>
</html>
<?php
mysql_free_result($rs_sitetext);

?>
 
difficult to know which query you're talking about. how about putting some hints into the die() strings?

one potential flaw is in the block below
Code:
           if (isset($_GET['page'])) {
                  $colname_rs_page = (get_magic_quotes_gpc()) ? $_GET['page'] : addslashes($_GET['page']);
                }
                mysql_select_db($database_spectrum, $spectrum);
                $query_rs_page = sprintf("SELECT * FROM spec_sitetext WHERE page = '%s'", $colname_rs_page);
                $rs_page = mysql_query($query_rs_page, $spectrum) or die(mysql_error());
                $row_rs_page = mysql_fetch_assoc($rs_page);
                $totalRows_rs_page = mysql_num_rows($rs_page);

it looks like you may be double quoting the page criteria as you have already added quotes in the gpc codesnip above. why are you not using the getsqlvalue function you have used elsewhere?

i assume you are using the gpc test for portability? personally i find the whole sprintf stuff just too cumbersome for extended use. i have moved completely to the PEAR db class for all my database needs. you don't need to worry about escaping query terms etc as the class handles it all for you transparently.
 
fyi: you can vastly improve the readability of your files by splitting the included parts into their own files and using the include() function:

Code:
$page = $_GET['page'];
switch($page) {
    case "Links":
        include("_links.php");
        break;
    case "aboutus":
        include("_aboutus.php");
        break;
    case "Main":
    default:
        include("_main.php");
        break;
}

-jeff
try { succeed(); } catch(E) { tryAgain(); } finally { rtfm(); }
i like your sleeves...they're real big
 
Its definately just something wrong with your sql. I agree with the ditching sprintf style. It has its place in certain situations but in my opinion, its much easier to just build a string with the . operator.

Code:
mysql_select_db($database_spectrum, $spectrum);
$query_rs_page = "SELECT * FROM spec_sitetext WHERE page = '$colname_rs_page'";
//die($query_rs_page);  <-- uncomment this to make sure it looks like valid sql.
$rs_page = mysql_query($query_rs_page, $spectrum) or die(mysql_error());
$row_rs_page = mysql_fetch_assoc($rs_page);
$totalRows_rs_page = mysql_num_rows($rs_page);
mysql_free_result($rs_page);

Note, when working with strings, using double quotes (") will allow variables to be inserted directly. You will also have to escape special characters. I generally use single quotes for safety.. then the only way to use special characters is to end the string.. like so

Code:
$query_rs_page = 'SELECT * FROM spec_sitetext WHERE page = "' . $colname_rs_page . '"';

I agree with jpadie.. insert some die() statements and track down exactly where the problem is at. FYI: The die() command will end execution immediately and output anything you pass in.. die("My variable was ".$myVarValue)

-Dustin
Rom 8:28
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top