PHP - Switch-case Q
can i do something like this?
Code: [Select] <?php switch ($i) { case 0: echo "i equals 0";?> ////////////// html stuff //////// <?php break; case 1: echo "i equals 1"; ?> ///////////////////html stuff////////////// <?php break; case 2: echo "i equals 2"; ?> ////////////html stuff/////////////// <?php break; } ?> Similar TutorialsHello, I am having a small issue with a case switch array that uses a range of data. I am using it to set the background of table cells depending on the data. I.E. 0-0.9, 1-1.9 etc with each one being a different color. Issue I am having is it doesn't change. It sets it based on the first array entry. What might I be missing? This is the first time I have used a case switch with a range.
-Thanks
$magScale = ''; switch($magnitude) { case myInterval >= 0 && myInterval <= 0.9: $magScale = 'rgb(195, 218, 236)'; break; case myInterval >= 1 && myInterval <= 1.9: $magScale = 'rgb(210, 238, 197)'; break; case myInterval >= 2 && myInterval <= 2.9: $magScale = 'rgb(244, 240, 202)'; break; case myInterval >= 3 && myInterval <= 3.9: $magScale = 'rgb(244, 223, 202)'; break; case myInterval >= 4 && myInterval <= 4.9: $magScale = 'rgb(240, 199, 205)'; break; case myInterval >= 5 && myInterval <= 10: $magScale = 'rgb(212, 195, 236)'; break; } Hi, I have been using an old contact form for a while now, this is it: Code: [Select] <?php if (isset($_POST['submit'])) { switch($_POST['contact_type']) { case 'Customer': $to = '...@gmail.com'; break; case 'HQ'; $to = '...@gmail.com'; break; case 'Office 2': $to = '...@gmail.com'; break; case 'Office 3': $to ='...@gmail.com'; break; case 'Office 4': $to = '...@gmail.com'; break; case 'Office 5': $to = '...@gmail.com'; break; } $subject = "WEBSITE ENQUIRY"; $name_field = $_POST['name']; $email_field = $_POST['email']; $message = $_POST['message']; if (strlen(trim($message)) > 0) { $body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message"; if (mail($to, $subject, $body)) { echo "<h3>Thanks! Your email has been sent <br />We will answer your enquiry as soon as possible.</h3>"; } else { echo 'Cannot sent mail'; } } else { echo "<h3>Error! <br />Please ensure that all fields are filled out in order to email us!</h3>"; } } else { echo "blarg!"; } ?> I recently extended the form with HTML5 etc and got a new form script, which makes a lot of improvements with the PHP. I want to put this on a site I am working on. The current form has an contact type pull down which changes the destination of the submitted form. It looks like this: Code: [Select] <?php if( isset($_POST) ){ //form validation vars $formok = true; $errors = array(); //sumbission data $ipaddress = $_SERVER['REMOTE_ADDR']; $date = date('d/m/Y'); $time = date('H:i:s'); //form data $name = $_POST['name']; $email = $_POST['email']; $telephone = $_POST['telephone']; $company = $_POST['company']; $enquiry = $_POST['enquiry']; $product = $_POST['product']; $message = $_POST['message']; //validate form data //validate name is not empty if(empty($name)){ $formok = false; $errors[] = "You have not entered a name"; } //validate email address is not empty if(empty($email)){ $formok = false; $errors[] = "You have not entered an email address"; //validate email address is valid }elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){ $formok = false; $errors[] = "You have not entered a valid email address"; } //validate company is not empty if(empty($company)){ $formok = false; $errors[] = "You have not entered a name"; } //validate message is not empty if(empty($message)){ $formok = false; $errors[] = "You have not entered a message"; } //validate message is greater than 20 charcters elseif(strlen($message) < 20){ $formok = false; $errors[] = "Your message must be greater than 20 characters"; } //send email if all is ok if($formok){ $headers = "From: user@mysite.com" . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $emailbody = "<p>You have recieved a new message from the enquiries form on your website.</p> <p><strong>Name: </strong> {$name} </p> <p><strong>Email Address: </strong> {$email} </p> <p><strong>Telephone: </strong> {$telephone} </p> <p><strong>Company: </strong> {$company} </p> <p><strong>Enquiry: </strong> {$enquiry} </p> <p><strong>Product of Interest: </strong> {$product} </p> <p><strong>Message: </strong> {$message} </p> <p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>"; mail("....@gmail.com","New Enquiry",$emailbody,$headers); } //what we need to return back to our form $returndata = array( 'posted_form_data' => array( 'name' => $name, 'email' => $email, 'telephone' => $telephone, 'company' => $company, 'enquiry' => $enquiry, 'product' => $product, 'message' => $message ), 'form_ok' => $formok, 'errors' => $errors ); //if this is not an ajax request if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){ //set session variables session_start(); $_SESSION['cf_returndata'] = $returndata; //redirect back to form header('location: ' . $_SERVER['HTTP_REFERER']); } } As you can see the new php form is much better, validates each field etc... I am having issues getting the case and switch statement into my new form though, can anyone please advise where to put it / what I need to take out to make it work? Its an important part of the form I need to make. Any help would be much appreciated. Hi, I have the following code: Code: [Select] <?php $cmd = $_GET['cmd']; if($cmd=="") { $cmd = "adminlogin";} // This creates the header for each of the installation pages switch($cmd) { // This is the installation agreement page case "adminlogin": print <<<LOGIN <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Member Site Maker 1.0</title> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <div id="head" align="center"> <h1 id="siteName">Member Site Maker </h1> <br /> <table align="center" border="0" bgcolor="#CCCCCC"> <tr> <td align="center"><span class=style1><b>ADMIN LOGIN</b></span></td> </tr> <tr> <td> <form action=admin.php?cmd=manage method=POST> Password: <input type=text name=password1> </td> </tr> <tr> <td> <input type=submit name=submit value=Submit> </td> </tr> </table> </form> LOGIN; break; // Managing Users case "manage": include_once("header.html"); include_once("data/password.php"); $password1 = $_POST['password1']; $password2 = base64_decode($password); if ($password1 != $password2) { print <<<BADLOGIN <table width=953 border=1 align=center bgcolor=#00CCFF> <tr> <td><span class=style1><b><center>Failed Login</center></b></span></td> </tr> <tr> <td><span class=style2>Your passwords do not match. Please go back and correct this error</td> </tr> </table> BADLOGIN; } else { echo <<<MANAGE <!--end navBar2 div --> <div id="navBar2"> <div id="sectionLinks"> <ul> <li><a href="admin.php?cmd=manage&password1=$password1">Manage</a></li> <li><a href="admin.php?cmd=dashboard&password1=$password1">Dashboard</a></li> <li><a href="admin.php?cmd=approval&password1=$password1">Approval</a></li> <li><a href="admin.php?cmd=msgcentre&password1=$password1">Message Center</a></li> <li><a href="admin.php?cmd=logins&password1=$password1">Logins</a></li> </ul> </div> </div> <!--end navBar2 div --> <div id="content"> <div class="story"> <table width="100%" border="0"> <tr> <td bgcolor="#99FF66"><div align="center"><span class="style3">Login</span></div></td> <td bgcolor="#99FF66"><div align="center"><span class="style3">Name</span></div></td> <td bgcolor="#99FF66"><div align="center"><span class="style3">Last Visited </span></div></td> <td bgcolor="#99FF66"><div align="center"><span class="style3">Registration Date </span></div></td> <td bgcolor="#99FF66"><div align="center"><span class="style3">Reset Password </span></div></td> <td bgcolor="#99FF66"><div align="center"><span class="style3">Delete</span></div></td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> </tr> </table> <h3> </h3> </div> </div> <!--end content --> MANAGE; } break; case "dashboard": break; case "approval": break; This works fine for when viewing the admin.php, I am asked for a password and then it compares the password against the encoded password before displaying the manage page. However this does not stop someone typing http://www.mysite.com/folder/admin.php?cmd=dashboard If they do that, it skips the password form and password check, and they can then go ahead and do whatever in the admin.php file. How can I prevent this, so that a password check is automatically done before allowing somebody to view the page? I have tried adding the code I used in the manage section, but it doesnt work again. Any help will be greatly appreciated, I been trying to work it out all day and run out of ideas. Many Thanks Hi I have a form that is popluated from the database now I am trying to get the switch case to be based on the option the user selects is this possible to make a case a variable popluated by the drop down if so can someone show me what am i missing? the value I am trying to get from the form to the switch case is the ( $val->slug) but the value not been set help please here the form Code: [Select] <form method="post"> <select name="deal-locations" onChange="this.form.submit()"> <?php while(list($key,$val) = each($locations)) { ?><option value="<?php echo $val->slug; ?>"><?php echo $val->slug; ?></option><?php } ?> </select> <input type="submit" value="submit"> </form> Here the switch case Code: [Select] switch ($_POST['deal-locations']) { case " $val->slug": echo "<h3>deal-locations: ASC</h3>"; $args = array( 's' => $_GET['s'], 'post_type' => 'deals', 'deal-locations' => ' $val->slug', 'where' => ' $val->slug', 'paged' => 'paged' ); break; } I'm testing out small bits of code for myself, and I'm trying to understand why this isn't coming out how I would imagine it to... I have my function which stores colors in an array from a text file, then I return back a random color from my array like so... function getColor() { $ball_color = explode("\n", file_get_contents('colors.txt')); // Takes file contents and stores them into an array. return $ball_color[array_rand($ball_color)]; } And now in the main program, I simply have this: $color = getColor(); switch($color) { Case "blue": // echo stuff break; Case "red": // echo stuff break; etc... } For some reason though, my switch statement always reads the default case, making me assume that the words "blue" "red" "green" etc... aren't matching up to what I have set the cases at. When I output what color is actually being read, it displays exactly as it should, so I don't understand why the case "red" isn't opening up when that color is chosen, or same with any of the other colors. Is there some small conflict I'm unaware of in this tiny practice code? Any help is appreciated, thanks. Morning, I'm working on a web site using a switch to separate different calls from a MySQL database. My style looks like this: <?php switch ($_GET['page']) { case 'news': echo ("NEWS HERE"); } break; case 'schedule'; echo ("SCHEDULE HERE"); } break; default: echo ("MAIN PAGE HERE"); break; } What I am trying to do, is specify that if the page is news, there can be an additional variable for id. I attempted before and after the break; for the news case, to make a new switch, but it isn't taking. I've looked around online, but can't find any information about this. Can anyone offer a hand? hey guys im having a few problems with my query if anyone can please help...the two problems im having is
1.the total price returning as 00106. price = 100.00 and p_and_p = 6.00 in the database...im after a figure that looks like 106.00
2. @category will be a parameter like :category which will be binded to a value like 'al'l, 'videos', 'dvd's', but if the parameter is ALL i dont want to join my categories table allowing it to select all rows regardless of the category
any help, pointer would be truly appreciated...thank you
SELECT @category := 'Videos', i.item_id, i.title, i.price, i.p_and_p, SUM(i.price + i.p_and_p) AS `total_price`, i.listing, i.condition, CONVERT_TZ(DATE_ADD(i.start_date_time, INTERVAL concat(i.listing_duration) DAY), '+00:00', u.time_zone) AS `end_date_time` FROM items i LEFT JOIN sub_categories sc ON sc.sub_category_id = i.sub_category_id CASE @category != 'All' THEN LEFT JOIN categories c ON c.name = 'Videos' END CASE JOIN users u WHERE u.user_id = '7' AND MATCH (i.title, i.description) AGAINST ('bla' IN BOOLEAN MODE) AND i.start_date_time < NOW() AND DATE_ADD(i.start_date_time, INTERVAL concat(i.listing_duration) DAY) >= NOW() GROUP BY i.i Hi, I have the following code: Code: [Select] case "Twitter"; echo 'Twitter gadget will show here'; break; I need to make it so it's like this: Code: [Select] case "Twitter" AND $member['top'] == "1" echo "Twitter Gadget will show here"; break; I need to add a IF onto the CASE is it possible? Thank you. I need to make the following code work without case sensitivity. For example, if this was processed, I would like for $message to be changed from "Stupid is not a nice word. Ugly is not nice either." to "unintelligent is not a nice word. unattractive is not nice either." For my purposes, I don't care that the capitalization changes, I just need the $goodwords to be replaced with the $badwords regardless of capitalization. Any ideas here? Code: [Select] <?php $message = "Stupid is not a nice word. Ugly is not nice either."; $badwords = array("stupid", "ugly"); $goodwords = array("unintelligent", "unattractive" ); $message = str_replace($badwords, $goodwords, $message); ?> How do I make the username and password checking CASE SENSITIVE? $result=sprintf("SELECT * FROM db WHERE username = '%s' AND watchword ='%s'", mysql_real_escape_string($username), mysql_real_escape_string($password)); Thanks. Bickey. hi, i just wanted to know... $arr[0] $arr[1] $arr[2] also this $arr[1] would be called a value, but how are the numbers 0,1 and 2 called? are that keys? didn't know where else to post this question. i've read and seen there are variations of what im trying to achieve but havent seen a exact example...what im trying to do is put a where clause in my query depending on if a set variable has a value
CASE WHEN (@category_id IS NOT NULL) THEN LEFT JOIN sub_categories sc ON sc.sub_category_id = i.sub_category_id JOIN categories c ON c.category_id = sc.category_id AND c.category_id = :category_id ENDis this possible or have i just got the syntax wrong somewhere...thank you guys I have this $str variable which say holds "String" and in my comparison I'm checking if it's content is "string" and it is supposed to return true but it isnt because of the case, how do I compare them without the case being an issue ? My case statement is not working. What happened is that two students got a $markgrade of 61 and 67. So they both should get grade B but instead they both get Grade A. 1 student got 55 which should be grade C but gets grade A. why is it not following the switch statement? Code: [Select] function outputModule($moduleID, $moduleName, $sessionData) { if(!count($sessionData)) { return false; } $markTotal = 0; $markGrade = 0; $weightSession = 0; $grade = ""; $sessionsHTML = ''; switch($grade){ case ($markGrade >=70): $grade = 'A'; break; case ($markGrade >=60 && $markGrade <=69): $grade = 'B'; break; case ($markGrade >=50 && $markGrade <=59): $grade = 'C'; break; case ($markGrade >=40 && $markGrade <=49): $grade = 'D'; break; case ($markGrade >=30 && $markGrade <=39): $grade = 'E'; break; case ($markGrade >=0 && $markGrade <=29): $grade = 'F'; break; }; foreach($sessionData as $session) { $sessionsHTML .= "<p><strong>Session:</strong> {$session['SessionId']} {$session['Mark']} {$session['SessionWeight']}%</p>\n"; $markTotal += ($session['Mark'] / 100 * $session['SessionWeight']); $weightSession += ($session['SessionWeight']); $markGrade = ($markTotal / $weightSession * 100); } $moduleHTML = "<p><br><strong>Module:</strong> {$moduleID} - {$moduleName} {$markTotal} {$markGrade} {$grade}</p>\n"; return $moduleHTML . $sessionsHTML; } Hi everyone,
On our school website, we've got a page where students can do a quiz, and get feedback given to them, as to whether their answers are correct or incorrect.
The code echos the student response for each question, and the feedback, tick / cross is displayed in the adjacent column.
However, I've just changed the input box from a text field to a text area, and I've noticed a little quirk.
The student answer, after pressing submit, now displays in lower case. Is their any way I can echo their answer, exactly as they input it.
Here is the relevant code:
<textarea name="user_answer_<?=$row_counter?>" cols="40" rows="2" /><?=$userAnswer?></textarea>Thanks for your time, Dave i want to make a simple forced lower case form but i got stuck on it
to begin with i want to everything user's write and submit convert to lowercase
am i using the right code? i'm not sure about using preg_match in this situation but i dont know what else to do don't be harsh with me i'm noob <?php if(isset($_GET['user'])&&!empty($_GET['user'])) { $user = $_GET['user']; if (preg_match('$englishUpperAlphabet'//English alphabet Upper case array//',$user)){ $user = mb_strtolower($user); echo $user; } else{ echo 'none'; }} ?> <form action="t.php" action="GET"> name: <input type="text" name="user" > <br> <input type="submit" value="submit" > </form> Is there a way to change the statement below so that it ignores case sensitivity of the variable? for instance, the statement would be true if $category == 'Admissions', 'ADMISSIONS', 'admissions', etc.
For some reason I'm having the worst time finding this via google search and know y'all will be able to help!
if ($category == 'Admissions') { echo ' <a href="#">-Forms</a><br /> <a href="#">-Tuition</a><br />'; } ?>Thanks! I am using preg_replace to automatically bold "$word" when it appears. It will only replace the word when capitalized. How can I get it to replace the word without being case sensitive. Also could I also throw a link in? I tried and I get a syntax error. I'm guessing the links in PHP are different than HTML Here is my code <?php $find ="/$word/"; $replace ="<b>$word</b>"; Echo preg_replace ($find, $replace, $definition); ?> Thanks when the simple search script in the tutorials on this site searches my mySQL database it doesnt find results unless they are typed in the same case as the original entry. ie 'horse' does not find 'Horse' is it some problem with my database table formats or do i need to add a bit of script to the search to solve it? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=317710.0 |