PHP - Checking For Multiple Values In A Switch Statement
Hi there,
I am working on a PHP web form. There is simple textbox where users can enter countries. If the user enters any of the European countries for example Spain, Germany or Italy then the web page must echo ' You entered a European country. The code I am using is: switch ($txtCountry) { case 'Germany' || 'Spain' || 'Belgium' || 'Cyprus' || 'Estonia': echo "You entered a European Country"; break; case 'Japan': echo "You entered a Far Eastern Country"; break; default: echo "Unknown Country"; break; } Now the problem is even if I enter a different country like Japan, it goes to the first Case: i.e. 'You entered a European Country' Whats the best way to use Switch case to check multiple values. Is my Syntax correct or do I need to use single quote of double quote here. Please reply. Thank you! Similar Tutorials
Table Issue - Multiple Location Values For User Pushes Values Out Of Row Instead Of Wrapping In Cell
Hello, Hi all, I am creating a switch page which will be acting as more of an index page for the different php files I have in my project. I have seven different pages and, I am a bit stuck as to what the order is and where the codes should go. I have got this far as is shown below: Code: [Select] <!--PHP Update--> <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("project1", $con); if ($_GET['action']=='delete_ok' and or){ }elseif ($_GET['action']=='edit_ok'){ } switch($_GET['action']){ case 'delete_ok': #########Delete OK Start################# //echo '<meta http-equiv="Refresh" content="0;URL=switch.php">'; #########Delete OK End ################# break; case 'edit_ok': break; } ?> <!--HTML--> <?php switch($_GET['action']){ case 'delete'; break; case 'edit'; echo 'Edit page'; ?> <form action="switch.php?action=edit_ok" method="post"> <?php break; default: echo "<table border='1'> <tr> <th>ID</th> <th>Date Of Birth</th> <th>Gender</th> <th>Title</th> <th>First Name</th> <th>Last Name</th> <th>Address Line 1</th> <th>Address Line 2</th> <th>City</th> <th>Postcode</th> <th>Contact No</th> <th>Email</th> <th>Additional Info</th> <th>Action</th> </tr>"; $result = mysql_query("SELECT * FROM project_data"); while($row = mysql_fetch_array($result)){ echo "<tr>"; echo "<td>" . $row['ID'] . "</td>"; echo "<td>" . $row['Date_Of_Birth'] . "</td>"; echo "<td>" . $row['Gender'] . "</td>"; echo "<td>" . $row['Title'] . "</td>"; echo "<td>" . $row['First_Name'] . "</td>"; echo "<td>" . $row['Last_Name'] . "</td>"; echo "<td>" . $row['Address_Line_1'] . "</td>"; echo "<td>" . $row['Address_Line_2'] . "</td>"; echo "<td>" . $row['City'] . "</td>"; echo "<td>" . $row['Postcode'] . "</td>"; echo "<td>" . $row['Contact_No'] . "</td>"; echo "<td>" . $row['Email'] . "</td>"; echo "<td>" . $row['Additional_Comment'] . "</td>"; echo "<td><a href='switch.php?action=edit&id=" . $row['ID']."'>Edit</a>  <a href='delete_write.php?id=" . $row['ID']."'>Delete</a></td>"; echo "</tr>"; } echo "</table>"; echo "<a href='write.php'>Insert</a>"; } mysql_close($con); ?> the file names a delete_write.php- deletes the data display.php- displays the data edit_write.php- editing the info edit_write_ok.php- edits on the database and shows on display.php write.php- this is the input page write_input.php- this inputs the data from write.php into the main database any help would be much appreciated. MOD EDIT: code tags added. $price = 0.00; switch($someValue) { case "One": $price = 1; break; case "Two": $total = $price + 2; echo $total break; } I'm having problem on this. Basically what i want is to use the value of $price in case "One" to case "Two". But it won't work. Any idea how to accomplish this? Thank you in advance. I couldn't understand switch statements in .net and I still don't get them with php. Can someone turn this into a switch statement, I just can't wrap my head around then. if (isset($_POST['news'])){ add($_POST['text']); header("location: admin.php"); } elseif (isset($_POST['rnews'])){ deletenews($_POST['number']); header("location: admin.php"); } elseif (isset($_POST['taddm'])){ taddmember($_POST['website'], $_POST['name']); header("location: admin.php"); } elseif (isset($_POST['tdelm'])){ tdeletemember($_POST['number']); header("location: admin.php"); } elseif (isset($_POST['addm'])){ addmember($_POST['website'], $_POST['name']); header("location: admin.php"); } elseif (isset($_POST['delm'])){ deletemember($_POST['number']); header("location: admin.php"); } elseif (isset($_POST['tnews'])){ tadd($_POST['text']); header("location: admin.php"); } elseif (isset($_POST['trnews'])){ tdelete($_POST['number']); header("location: admin.php"); } elseif (isset($_POST['video'])){ videoupdate($_POST['link']); header("location: admin.php"); } else { echo " Failed"; } when you build a switch, does it have to have a default case? If so, is there a way to get it to default to the first case instead of re posting the code in the default? Code: [Select] <?php echo '<form action="hwCase.php" method="post"> Enter number <input type="text" name="number"/><br /> </form>'; $input = $_POST['number']; // if a number is entered in the form, ie not null if (isset($input)) { switch ($input) { // if number entered is less than 0, ie negative number case ($input<0): echo "Enter a positive number."; break; // if number entered is greater than 1000 case ($input>1000): echo "Enter a number less than 1000."; break; // if number entered is not a number, ie a letter, a character case (!ctype_digit($input)): echo "<br><img src=\"squidward.jpg\"><br><br>Enter a valid number. "; break; // if valid number is entered, loop "hello world" that many times case (($input>0) && ($input<1000)): echo "hello world " . $input . "<br />"; break; // if anything else is entered default: echo "Enter a number."; break; } } // if no number is entered in the form, ie null else { echo "Please enter a number."; } ?> For some reason, my loop doesn't work. Please help me fix it! Thanks in advance! I need to loop this part: Code: [Select] case (($input>0) && ($input<1000)): echo "hello world " . $input . "<br />"; break; i am trying to get the allowed file types from the database into a switch statement but with no luck so far. They types are in the database like: jpg, png, gif. All seperated with a comma and all in one db column. I am then splitting them at the comma and inserting them into $file_list. In the switch statement i want it to be like: switch($ext) { case "jpg": case "png": case "gif": break; } how can i make this possible? here is my code so far: $ext = strtolower(pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION)); $f_types = $f_types_info['file_types']; $f_types = preg_split("|\,|", $f_types); $types = count($f_types); $file_list = ""; for($i=0; $i<$types; $i++) { $file_list .= $f_types[$i]; } switch ($ext) { case $file_list: break; default: $error = "File Type Not Allowed"; break; } I have database that is a list of categories that I would like to insert into a switch statement. This is the only way that I know how to do it right off hand and of course it doesn't work. I've looked on the internet and found examples but they are slightly over my head as ways to do it. Depending on $group which comes from the url a title an h1 would be assigned. Code: [Select] $q = "SELECT * FROM categories"; $r = @mysqli_query ($dbc, $q); switch ($group) { if ($r) { //If $r ran OK while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){ case '$row['id_cat']': $h1 = '.$row['group']'; break; } } } Thanks S Hello Everyone, I have to change the if statements to a switch statement, in this game. Can anyone help? Thanks. var checkKeyPressed = function (e) { // Press key A or key D to make dog run to the left or right // The running speed is specified by the step variable, 10 by default. // If you replace 10 with a larger integer, the dog will run faster. //press A, dog runs left if (e.keyCode == "65") { if (prex[0] > 5) { prex[0] = prex[0] - step; } } //press D, dog runs right if (e.keyCode == "68") { if (prex[0] < right) { prex[0] = prex[0] + step; } } }; I am trying to to create an if statement checking the domain name. I need to check the domain with "www" and without the "www". How can I make an OR inside an if statement "||" doesn't seem to work? I have tried this code, but doesn't work: if (($_SERVER['HTTP_HOST'] != 'www.domain.com')||($_SERVER['HTTP_HOST'] != 'domain.com')){ echo "some text here":} Hey guys, I have a mysql switch statement that shows different things based on the row value. Here it is... <?php switch ($rows['icon']) { case 1: $picture = '<img src=\"img/apple.gif\" title=\"apple\" alt=\"apple\" />'; echo $picture; break; case 2: $picture = '<img src=\"img/banana.gif\" title=\"banana\" alt=\"banana\" />'; echo $picture; break; case 3: $picture = '<img src=\"img/orange.gif\" title=\"orange\" alt=\"orange\" />'; echo $picture; break; default: echo "$rows[icon] is something other than 1 2 or 3"; break; } ?> Here is how the other code looks like. <?php error_reporting(E_ALL); ini_set('display_errors', '1'); mysql_connect("localhost", "", "")or die("cannot connect"); mysql_select_db("test")or die("cannot select DB"); $tbl_name="test_mysql"; $sql="SELECT * FROM $tbl_name"; $result=mysql_query($sql); $count=mysql_num_rows($result); if (isset($_POST['Submit'])) { for($i=0;$i<$count;$i++){ $month = $_POST['month']; $date = $_POST['date']; $message = $_POST['message']; $title = $_POST['title']; $id = $_POST['id']; $icon = $_POST['icon']; // ILYA $monthday= $month[$i]."<br>".$date[$i]; $sql1="UPDATE $tbl_name SET monthday='$monthday', month='$month[$i]', date='$date[$i]', message='" . mysql_real_escape_string($message[$i]) . "', title='" . mysql_real_escape_string($title[$i]) . "', icon='$icon[$i]' WHERE id=".$id[$i]; // ILYA if(!($result1 = mysql_query($sql1))){ "<BR>Error UPDATING $tbl_name "; exit(); } } } $result=mysql_query($sql); $count=mysql_num_rows($result); ?> Dont mind the other UPDATE code its part of something else. Anyways, why is the case automaticaly going to the last one... with the words: is something other than 1 2 or 3 Also, this is with multiple rows at once so I think that that may the problem... I am trying to check to see if a file size is acceptable before an upload but cant seem to get the right result no matter what i do. if i have my if statement below coded like this Code: [Select] if($_FILES["upload"]["size"] < 1024000){ echo'entered if statement<br />'; } else{ echo'entered else statement<br />'; } Then i always am entereing the if statememnt but if i have my if statement like this Code: [Select] if($_FILES["upload"]["size"] > 1024000){ echo'entered if statement<br />'; } else{ echo'entered else statement<br />'; } then i always seem to enter the else staement. I have tried with a VIREITY of differnt size files some from like 2kb to 10mb... i believe somewhere near the > or < is my problem but i dont seem to see it This is my registering script: <?php include('connectvars.php'); $user_email = strip_tags(trim($_POST['email'])); $firstname = strip_tags(trim($_POST['firstname'])); $lastname = strip_tags(trim($_POST['lastname'])); $nickname = strip_tags(trim($_POST['nickname'])); $password = strip_tags($_POST['password']); $repassword = strip_tags($_POST['repassword']); $dob = $_POST['dob']; $find_us_question = strip_tags(trim($_POST['find_us_question'])); if (isset($_POST['submit_signup'])) { if ((empty($user_email)) || (empty($firstname)) || (empty($lastname)) || (empty($nickname)) || (empty($password)) || (empty($dob))) { echo "Please fill out all the fields!"; } else { // check char length of input data if (($nickname > 30) || ($firstname > 30) || ($lastname > 30) || ($user_email > 50)) { echo "Your nickname, first- and/or lastname seem to be too long, please make sure you have them below the maximum allowed length of 30 characters!"; } else { // check password char length if (($password > 25) || ($password < 6)) { echo "Your password must be between 6 and 25 characters!"; } else { // encrypt password $password = sha1($password); $repassword = sha1($repassword); if ($password != $repassword) { echo "Please make sure your passwords are matching!"; } else { $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $query = sprintf("INSERT INTO user (firstname, lastname, nickname, password, email, dob, doj) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', now())", mysqli_real_escape_string($dbc, $firstname), mysqli_real_escape_string($dbc, $lastname), mysqli_real_escape_string($dbc, $nickname), mysqli_real_escape_string($dbc, $password), mysqli_real_escape_string($dbc, $user_email), $dob); mysqli_query($dbc, $query); mysqli_close($dbc); echo "You have been successfully registered!"; } } } } } ?> A bunch of nested if statements, the read-ability gets worse after a while, I'm new to programming so I don't know if there's a better more read-able solution. Anyway, every time I try to sign up it's printing out the echo message: "Your password must be between 6 and 25 characters!" Which derives from: // check password char length if (($password > 25) || ($password < 6)) { echo "Your password must be between 6 and 25 characters!"; } else { EVEN if I stay between 6 and 25 characters it's still printing out this error message, let's say I have a password of 8 characters, and I've entered everything else correctly, it's still giving me all the time this error message, and I can not figure out why. Hi! I have this to check if now is between start time and end time: [date_default_timezone_set('Europe/Belgrade'); $TimeNow = date("H:i" ,time()); $today_date = date('d-m-y'); $GetTimeTable = "SELECT * FROM timetable WHERE username='$username' AND Subject_date='$today_date'"; $ConnectTimeTable = $database->query($GetTimeTable); $TimeTable = mysql_fetch_array($ConnectTimeTable); $Subject = $TimeTable['Subject']; $Start_time = $TimeTable['Start_Time']; $End_time = $TimeTable['End_Time']; ?><br><? if($TimeNow >= $Start_time && $TimeNow <= $End_time){ echo "Current Class: "; echo $Subject; echo "<br><br>"; // a START time value $start = $TimeNow; // an END time value $end = $End_time; // what is the time difference between $end and $start? if( $diff=@get_time_difference($start, $end) ) { echo "Time left: " . sprintf( '%02d:%02d', $diff['hours'], $diff['minutes'] ); } else { echo "Hours: Error"; } } else{ echo "No class. :)"; } Start time and end time is displayed in the format like 14:26. For some reason this code doesn't work though, I don't get why. Hello ,
I am trying to update a record in my table if the particular value exists in the rows of a table. But my if-else not working properly. I am not getting where i am going wrong.
here is my table authorization, where i define authorization % with min and max.
authorisation.JPG 16.83KB
0 downloads
after adding line items, before display i will check whether any one of the line item discount lies within this min and max and also checks whether authorization is required (required='Yes'/'No') for that discount in my authorization table. If authorization required then i will update that order number as authorized.
here is my line items table
line_items.JPG 20.37KB
0 downloads
I am doing like this
while($row=mysql_fetch_array($query)) { $dis1 = "SELECT auth_id, auth_min, auth_max, required FROM sales_authorisation"; $dis2 = mysql_query($dis1) or die (mysql_error()); while($d1 = mysql_fetch_array($dis2)) { $min = $d1['auth_min']; $max = $d1['auth_max']; $req = $d1['required']; //echo $req; if( ($min <= ($row['discount'])) && ($max >= ($row['discount'])) && ($req='Yes')) { $auth = "UPDATE orders SET authorise='No' WHERE order_id=".$order_id.""; echo "hello"; } else { $auth = "UPDATE orders SET authorise='Yes' WHERE order_id=".$order_id.""; } $auth1 = mysql_query($auth) or die (mysql_error()); } ?> <tr> <td><?php echo $counter++; ?></td> <td><?php echo $row['itemname']; ?> - <?php echo $row['uom']; ?></td> <td><?php echo $row['description']; ?></td> <td><?php echo $row['quantity']; ?></td> <td><?php echo number_format($row['selling_price'],2); ?></td> <td><?php echo $row['discount']; ?> %</td> <td><?php echo $row['tname']; ?>-<?php echo $row['rate']; ?> %</td> <td><?php echo $row['freight']; ?></td> <td><?php echo number_format($row['total'],2); ?></td> </tr>While loop is for displaying line items for the order. But my if condition doesn't works . Not getting how to do it. please suggest i retrieving an adid from $_GET which is also a value retireved from a database. Code: [Select] $this_adid=$_GET['adid']; if(empty($this_adid)) { $get_ad_id = mysql_query("SELECT userid FROM ads WHERE adid='$this_adid'", $con) or die("Error Getting AD ID: ".mysql_error()); while($get_ad_id_results = mysql_fetch_assoc($get_ad_id)) { $owner_id=$get_ad_id_results['userid']; } } the above query works if $this_adid returns 0 (http://www.website.com/?do=delete&adid=0&givenuserid=15773) i.e. adid is 0 in the table. But it does not work if $this_adid returns null or ntohin (http://www.website.com/?do=delete&adid=&givenuserid=15773) .i.e adid is ' ' (empty) field in the databse table.. can someone tell me why it does not check for null or empty values properly? Hello,
I am trying to check whether the values in rows are equal or same?
I have two tables orders and line_items. I will store more than 1 line items in line_items table with the same order_id getting from orders table. In line items if i have 3 line items for same order_id, when each line items gets dispatched i will set the status to 'Dispatched' in line_items table. When all the 3 becomes 'Dispatched', i will update the order status as 'Completed' in orders table.
Now i am not getting how to check whether all the 3 line items status id 'Dispatched'.
I tried doing like this
$q1 = "select orders.order_id, orders.item_status as istatus, orders.status as ostatus, orders.authorise, line_items.order_id, line_items.status as bstatus, COUNT(line_items.id) as bid from orders inner join line_items on orders.order_id=line_items.order_id where line_items.order_id=".$id." AND line_items.id<>'Dispatched'"; $q2 = mysql_query($q1); while($q3 = mysql_fetch_array($q2)) { echo $q3['bstatus']; if($q3['bstatus']==''); { echo "HELLLOOOO"; } }But its not working. It goes into if loop even if a single value is 'Dispatched' Please help me. Hi, My company has 240+ locations and as such some users (general managers) cover multiple sites. When I run a query to pull user information, when the user has multiple sites to his or her name, its adds the second / third sites to the next columns, rather than wrapping it inside the same table cell. It also works the opposite way, if a piece of data is missing in the database and is blank, its pull the following columns in. Both cases mess up the table and formatting. I'm extremely new to any kind of programming and maybe this isn't the forum for this question but figured I'd give it a chance since I'm stuck. The HTML/PHP code is below: <table id="datatables-column-search-select-inputs" class="table table-striped" style="width:100%"> <thead> <tr> <th>ID</th> <th>FirstName</th> <th>LastName</th> <th>Username</th> <th>Phone #</th> <th>Location</th> <th>Title</th> <th>Role</th> <th>Actions</th> </tr> </thead> <tbody> <?php //QUERY TO SELECT ALL USERS FROM DATABASE $query = "SELECT * FROM users"; $select_users = mysqli_query($connection,$query);
// SET VARIABLE TO ARRAY FROM QUERY while($row = mysqli_fetch_assoc($select_users)) { $user_id = $row['user_id']; $user_firstname = $row['user_firstname']; $user_lastname = $row['user_lastname']; $username = $row['username']; $user_phone = $row['user_phone']; $user_image = $row['user_image']; $user_title_id = $row['user_title_id']; $user_role_id = $row['user_role_id'];
// POPULATES DATA INTO THE TABLE echo "<tr>"; echo "<td>{$user_id}</td>"; echo "<td>{$user_firstname}</td>"; echo "<td>{$user_lastname}</td>"; echo "<td>{$username}</td>"; echo "<td>{$user_phone}</td>";
//PULL SITE STATUS BASED ON SITE STATUS ID $query = "SELECT * FROM sites WHERE site_manager_id = {$user_id} "; $select_site = mysqli_query($connection, $query); while($row = mysqli_fetch_assoc($select_site)) { $site_name = $row['site_name']; echo "<td>{$site_name}</td>"; } echo "<td>{$user_title_id}</td>"; echo "<td>{$user_role_id}</td>"; echo "<td class='table-action'> <a href='#'><i class='align-middle' data-feather='edit-2'></i></a> <a href='#'><i class='align-middle' data-feather='trash'></i></a> </td>"; //echo "<td><a href='users.php?source=edit_user&p_id={$user_id}'>Edit</a></td>"; echo "</tr>"; } ?>
<tr> <td>ID</td> <td>FirstName</td> <td>LastName</td> <td>Username</td> <td>Phone #</td> <td>Location</td> <td>Title</td> <td>Role</td> <td class="table-action"> <a href="#"><i class="align-middle" data-feather="edit-2"></i></a> <a href="#"><i class="align-middle" data-feather="trash"></i></a> </td> </tr> </tbody> <tfoot> <tr> <th>ID</th> <th>FirstName</th> <th>LastName</th> <th>Username</th> <th>Phone #</th> <th>Location</th> <th>Title</th> <th>Role</th> </tr> </tfoot> </table>
I read ages ago (and checked to see if it's true, it was and given how it works, it must still be) the end user can alter the value of any form field, using Firebug or similar, before submitting it. Two things I've figured out today: 1) a form input doesn't need a value - doesn't even need the attribute - if you're only checking whether the POST var isset and the actual value isn't important 2) Although it appears not to matter in the example I'm working on now, if the script doesn't check what the value is, and potentially sanitise it, the user could submit the form with any value, true, false, malicious, idk... So my question is: is this one of the ways malicious bad things can happen and do I *have to* specify a value, not because the script won't work without it, it does, but because in the real world it opens a security door if I don't check for malicious script by saying "if value not as expected, script has to die". Having formulated the question properly and thought about it I can't imagine simply making a form, without obvious connections to anything important, could be a problem in the way I'm asking about but I asked it now so Edited by appobs, 03 July 2014 - 12:08 PM. What I want to do is run both '$intel_mod' and '$op_intel_mod' in that if statement and output 2 different variables for both of them. e.g: So '$intel_mod' goes in and comes out as '$int_mod = 0.85' Then '$op_intel_mod' should go in and come out as '$op_int_mod'. Somthing like that is what im after, im now thinking this is not the way to do it or I should be using a loop? Code: [Select] $intel_mod = $user_int/$op_int; $op_intel_mod = $op_int/$user_int; if($intel_mod < 0.20) { $int_mod = 0.75; } elseif($intel_mod < 0.40){ $int_mod = 0.80; } elseif($intel_mod < 0.60){ $int_mod = 0.85; } elseif($intel_mod < 0.80){ $int_mod = 0.90; } elseif($intel_mod < 0.1){ $int_mod = 0.95; } elseif($intel_mod == 1){ $int_mod = 1; } elseif($intel_mod > 2){ $int_mod = 1.10; } elseif($intel_mod > 3){ $int_mod = 1.20; } elseif($intel_mod > 4){ $int_mod = 1.30; } elseif($intel_mod > 5){ $int_mod = 1.40; } elseif($intel_mod > 0.20){ $int_mod = 1.50; } Any help would be great, Ruddy |