So I have this commands handling:
$message = the entered message.
public function handleCommands($message, $username)
{
//Variables we're going to use
$space = strpos($message, ' '); # The first space.
$command = trim(substr($message, 1, $space)); # The command after the slash
$name = substr($message, $space + 1); # The name after the command.
switch ($command)
{
case 'ban':
$this->ban($name, $username);
break;
case 'prune':
$this->prune($username);
break;
case '':
echo 'Please use a command!';
break;
case 'test':
try
{
$this->test($name);
}
catch (exception $r)
{
echo $r->getMessage();
}
break;
}
}
This basically will check for the command.
$command = the entered word after the slash ( " / " ).
Can you see
case '':
This basically checks if there is no command after the slash.
Question: I want the system to check aswell, if the command exists in the cases.
For example:
user wrote:
/hello
But that command doesn't exists, considering we only have case 'ban', case 'prune', case 'test' and case ''.
there is no case 'hello', so it will throw an error.
Is there a function that does this sort of thing? How can I do this?
I believe what you're looking for is a default: case.
Example:
<?php
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?>
EDIT:
Fixed version of problem that was chatted about: http://privatepaste.com/bd34e7e63b
Use the case default:
switch ($command)
{
case 'ban':
$this->ban($name, $username);
break;
case 'prune':
$this->prune($username);
break;
case '':
echo 'Please use a command!';
break;
case 'test':
try
{
$this->test($name);
}
catch (exception $r)
{
echo $r->getMessage();
}
break;
default:
echo "That command does not exist.";
}
Related
I would like to ask if it's possible to have a switch statement inside a php file where it is in mpdf.
this is my switch statement
switch($cts){
case 1:
echo "Not at all";
break;
Case 2:
echo "Ok";
break;
default;
echo "none";
}
but this could not be done in a mpdf.
Help.
You could store the respective messages in a variable and print it out outside the switch.
$msg = '';
switch($cts){
case 1:
$msg = "Not at all";
break;
case 2:
$msg = "Ok";
break;
default: $msg = "none";
}
echo $msg;
I have the following switch statement.
The URL contains a referral ID e.g twitter, facebook or an email e.g mail#mail.com. This is stored as $ref
I have the following switch statement:
switch ($ref) {
case "twitter":
echo "twitter";
break;
case "facebook":
echo "facbeook";
break;
case "blog":
echo "blog";
break;
case strstr($ref,'#'):
echo "email = ".$ref;
default:
echo "no referral found";
break;
}
However if URL is passed with nothing (e.g just www.mything.co.uk) then I wish to go to the default case.
Instead, I get the following output:
email = no referral found
Why does the default also include the text I set for case strstr($ref,'#') ?
OP question: "Why does the default also include the text I set for case strstr($ref,'#') ?"
Answer: there's no break; following the output, and thus falls through to the default case.
UPDATE: Addressing the issue of putting a statement within a case, I'm also including an easy work-around:
switch ($ref) {
case "twitter":
echo "twitter";
break;
case "facebook":
echo "facbeook";
break;
case "blog":
echo "blog";
break;
default:
if (strstr($ref,'#')) {
echo "email = ".$ref;
} else {
echo "no referral found";
}
break;
}
When $ref is an empty String, then strstr($ref,'#'); returns an empty string too, this is why the case strstr($ref,'#'): matches the switch input $ref.
The problem is, you can't even use a email validation function like
filter_var($ref, FILTER_VALIDATE_EMAIL)
That would return false in case of an empty input instead of an empty string, but switch does loose comparison, meaning that an "" == false would return true:
http://php.net/manual/en/types.comparisons.php#types.comparisions-loose
Thus the only solution I see is to use an if statement using the === operator:
if($ref == 'twitter') {
echo "twitter";
} else if($ref == 'facebook') {
echo "facbeook";
} else if($ref == 'blog') {
echo "blog";
} else if($ref === filter_var($ref, FILTER_VALIDATE_EMAIL)) {
echo "email = ".$ref;
} else {
echo "no referral found";
}
That's because your test is performed like if ($ref == strstr($ref, '#')), where strstr returns false which equals an empty string. You cannot really use dynamic comparisons in switch statements. Use if..else if you need that. Alternatively, abuse switch a bit:
switch (true) {
case $ref == 'twitter':
..
case strstr($ref, '#'):
..
}
That will work:
case (strstr($ref, '#') ? true : false):
But it's not really good of practice.
I'm try to send a value to a PHP file, but when I check, this value became null.
I send the value by: user_login.php?p_action=New_User
The code of user_login.php is:
require("include/session_inc.php");
require("include/user_handling_inc.php");
require("include/db_inc.php");
start_Session(false, false);
switch ($p_action) {
case 'Login': {
$l_flag = verify_User($p_in_username, $p_in_password);
if ($l_flag == "Not_Found") {
$l_flag = "New_User";
}
break;
}
case 'Save_Profile': {
$l_flag = "Save_Profile";
break;
}
case 'New_User':
$l_flag = "New_User";
break;
case 'Create_New_User':
$l_flag = "Create_New_User";
}
switch ($l_flag) {
case 'New_User': {
include "include/user_new_inc.php";
break;
}
case 'Save_Profile': {
load_User_Data(" username = '$p_in_username' ", false);
include "include/user_profile_save_inc.php";
break;
}
case 'Wrong_Password':
echo "Wrong Pass";
break;
case 'OK':
load_User_Data(" username = '$p_in_username' ", true);
store_User_Cookie($g_userdata->user_id);
include "include/user_profile_inc.php";
break;
case 'Create_New_User':
$l_user_id = create_New_User ($p_in_username, $p_in_email, 'Y');
if ($l_user_id != -1) {
store_User_Cookie($l_user_id);
echo "Success !! <br><br> \n";
echo "<a href\"/index.php\"> Back to Main </a>";
}
break;
}
First your code isn't correct please read more about using Switch here
second to access to any variable came from url you can use Global variable $_GET or $_REQUEST
and you can read more about them from here and here
and this is your code after fixing it please try to run it
<?php
require("include/session_inc.php");
require("include/user_handling_inc.php");
require("include/db_inc.php");
start_Session(false, false);
$p_action=$_GET["p_action"];
switch ($p_action) {
case 'Login':
$l_flag = verify_User($p_in_username, $p_in_password);
if ($l_flag == "Not_Found") {
$l_flag = "New_User";
}
break;
case 'Save_Profile':
$l_flag = "Save_Profile";
break;
case 'New_User':
$l_flag = "New_User";
break;
case 'Create_New_User':
$l_flag = "Create_New_User";
break;
}
switch ($l_flag) {
case 'New_User':
include "include/user_new_inc.php";
break;
case 'Save_Profile':
load_User_Data(" username = '$p_in_username' ", false);
include "include/user_profile_save_inc.php";
break;
case 'Wrong_Password':
echo "Wrong Pass";
break;
case 'OK':
load_User_Data(" username = '$p_in_username' ", true);
store_User_Cookie($g_userdata->user_id);
include "include/user_profile_inc.php";
break;
case 'Create_New_User':
$l_user_id = create_New_User ($p_in_username, $p_in_email, 'Y');
if ($l_user_id != -1) {
store_User_Cookie($l_user_id);
echo "Success !! <br><br> \n";
echo "<a href\"/index.php\"> Back to Main </a>";
}
break;
}
?>
you need to make the code like this friend
switch ($_GET["p_action"]) {
case 'Login': {
$l_flag = verify_User($p_in_username, $p_in_password);
if ($l_flag == "Not_Found") {
$l_flag = "New_User";
}
that well give you the value of the get!!!
Use $_GET to get your parameter.
Sometimes $_REQUEST is preferable since it access both get & post data.
2nd thing never trust the user input so you must use addslashes(); or real_escape_string() function to prevent attacks on the system.
So Code would be like this :
$var = addslashes($_GET['p_action']);
switch($p) {
case 'Login':
$l_flag = verify_User($p_in_username, $p_in_password);
if ($l_flag == "Not_Found") {
$l_flag = "New_User";
}
break;
"OTHER CASES HERE"
}
Notice that : Don't add { } for CASE. Read syntax for switch
here.
I use the class below to route all requests for php on my web application. Can I improve upon this?
/*route*/
class route
{
function __construct($a)
{
if(isset($_FILES['ufile']['tmp_name'])) // handles file uploads
{
new upload();
}
elseif(isset($_POST['a'])) // handles AJAX
{
$b=$_POST['a'];
switch($b)
{
case '0':
new signin();
break;
case '1':
new signup();
break;
case '2':
session::finish();
break;
case '3':
new bookmark('insert');
break;
case '3a':
new bookmark('delete');
break;
case '4':
new tweet();
break;
default:
echo "ajax route not found";
break;
}
}
elseif($a!=0) // handles views
{
new view($a);
}
else
{
// route not found
}
}
}
Verification(passes)
/*ROUTE
// Test Code - create entry
new route(0);
new route(1);
$_FILES['ufile']['tmp_name']='test file';
new route(0);
unset($_FILES['ufile']['tmp_name']);
$_POST['a']=0;
new route(0);
// Test Cases
// Case 0: echo "not routed: <br>";
// Case 1: echo "view created: $a <br>";
// Case 2: echo "file uploaded <br>";
// Case 3: echo "ajax responded: <br>";
*/
public static function route($a)
{
// The first if statement is redundant this line will accomplish the
// same as the if/else because if post[a] is not set it will become null
$b=$_POST["a"];
// now that b is a, it's really one switch statement
if( $b==0 && $a==0 )
switch( $b )
{
case '0':
new signin();
break;
case '1':
new signup();
general::upload();
break;
case '2':
session::finish();
break;
case '3':
new bookmark('insert');
break;
case '3a':
new bookmark('delete');
break;
case '4':
new tweet();
break;
default:
view::posts_all();
break
}
}elseif( $a==1 )
view::bookmarks();
else
view::posts_all();
Give that a go, Good luck. (A side note: the quotation marks on the numeric cases are optional, the 3a is not. I left them in there because they were in the original. You could reduce it further by getting rid of $b entirely and running the switch on $_POST['a'] )
if/else statement lets you set particular condition evaluations, while switch/case only lets you set some particular values that the variable may assume (i.e. in a switch/case you cannot say something like $b > 10).
Except for that, there's no much difference between if/else or switch/case.
I suggest you to you use switch/case construct, since you are just comparing $b with a group of constants.
Besides, remember premature optimization is the root of all evil :)
I am creating a report with the data which calls the stored procedure and that procedure returns
various sections (1,2,3,4,5,6) with the data in each section.Now the sections may contain or may
not contain the data.This is how i have wriiten my logic
foreach($this->$dbresults as $row){
$var1 ='';
If($var1!=$row['section']){
switch($row['section']){
case '1':echo "some thing data";
break;
case '2':echo "some thing data";
break;
case '3':echo "some thing data";
break;
case '4':echo "some thing data";
break;
case '5':echo "some thing data";
break;
case '6':echo "some thing data";
break;
}
}
$var1=$row['section']
}
So here My problem if any one of the section is not present then that section case cannot be executed
.I mean How do i execute the section even if the section is not returned from the database
I guess you're already ordering your results by section. If your sections are really 1-n, you could put your switch() code into some runsections function and do this:
$var1=0; $lastsection=16;
foreach($this->dbresults as $row) {
If($var1!=$row['section']){
for($num=$var1+1; $num<$row['section']; $num++) runsections($num);
runsections($row['section']);
}
$var1=$row['section'];
}
for($num=$var1+1;$num<=$lastsection;$num++) runsections($num);
if your sections aren't sequential numbers you could create an array and check if they've all been executed
$sections=array('a'=>0,'b'=>0,'c'=>0,'d'=>0,'e'=>0);
If($var1!=$row['section']){
unset($sections[$row['section']]);
runsection($row['section']);
}
...
}
foreach($sections as $num) {
runsection($num);
}
edit: so the runsections() function would look like this:
function runsections($section) {
switch($section){
case '1':echo "some thing data";
break;
case '2':echo "some thing data";
break;
case '3':echo "some thing data";
break;
case '4':echo "some thing data";
break;
case '5':echo "some thing data";
break;
case '6':echo "some thing data";
break;
}
}
switch($x){
case '1':
echo "some thing 1";
break;
case '2':
echo "some thing 2";
break;
case 'N':
echo "some thing N";
break;
default:
echo "some thing else";
}
After your last case, insert:
default: echo "some error";
The break is optional since it's the last case in the switch statement. Also, The single quotes are also optional if you're looking for numeric options.
case 1: echo "something";
break;
Maybe I am not quite understanding exactly what you want. The following code should work in the following conditions:
You always want to display the 6
sections with either DB data or
non-DB data.
You do not need to display the same
section multiple times.
$sections = range(1, 6);
foreach($sections as $sectionNum) {
$sectionNum = (string) $sectionNum;
$foundSection = false;
foreach($this->dbresults as $row) {
if ($row['section'] == $sectionNum) {
echo "section #$sectionNum has DB data: " . $row['data'];
$foundSection = true;
break;
}
}
if (!$foundSection) {
echo "section #$sectionNum does not have DB data.";
}
}
Here's what I've got:
foreach($this->dbresults as $row){
if(isset($row['section'])){
switch($row['section']){
case '1':echo "some thing data";
break;
case '2':echo "some thing data";
break;
case '3':echo "some thing data";
break;
case '4':echo "some thing data";
break;
case '5':echo "some thing data";
break;
case '6':echo "some thing data";
break;
default:echo "some thing data";
break;
}
} else {
//Do something since no section data was stored
}
}
I added a default case, fixed the small php errors ($this->$dbresults is changed, using isset instead of !='') and added an else to your if to do something if the section isn't found.