PHP - Proper Use Of Multiple If Statements?
Hi.
Currently I have code the uses both TRUE. IF statements and FALSE statements to move on. For example. Is it better to use: Code: [Select] Where B=A C=A IF A=B { IF C=B{ ECHO 'HELLO WORLD'; }ELSE ECHO 'C DOES NOT EQUAL B'; }ELSE ECHO 'A DOES NOT EQUAL B'; ' OR is it better to do it like this: Code: [Select] Where B=A C=A IF A<>B { ECHO 'C DOES NOT EQUAL B'; ELSE IF C<>B{ ECHO 'C DOES NOT EQUAL B'; ELSE ECHO 'HELLO WORLD'; '[/code Similar TutorialsJust curious, what is proper programming in cases where you're just doing a simple IF statement where there really is no need for an ELSE. Should you still write out the ELSE? For example, which is proper... Code: [Select] if (x=1) { //code here to do something } or Code: [Select] if (x=1) { //code here to do something } else { } There would be nothing in the ELSE statement, so is it OK to just leave it out completely (i.e. version #1), or is it proper to still have it listed (i.e. version #2)? Hi guys, I am just wondering if there is a proper method to streamline my codes, whenever I perform multiple INSERTs into tables? Probably like INNER JOIN method etc? Thanks $query = "INSERT INTO practice_user (name, email, password, dob, category, comments) VALUES ('$name', '$email', '$password', '$dob', '$category', '$comments')"; $result = mysqli_query($dbc, $query) or die(mysql_error()); $query2 = "INSERT INTO location (name) VALUES ('$location')"; $result = mysqli_query($dbc, $query2) or die(mysql_error()); Hi There, Im trying to figure out how to do this if/else statement. I need it to say, "if this is true, do this. if this is true, do this. If neither is true, do this. So there are three different possible outcomes. I tried to put each new if inside of the previous else. but that doesn't seem to work. $firstname = $_REQUEST['firstname']; $lastname = $_REQUEST['lastname']; if ($firstname == 'Joey' and $lastname == 'Hodara') { $output = 'Welcome to our site, ' . htmlspecialchars($firstname, ENT_QUOTES, 'UTF-8') . ', Oh Glorious Leader!'; } else { if ($firstname == 'Matt' and $lastname == 'Fig') { $output = 'Welcome to our site, ' . htmlspecialchars($firstname, ENT_QUOTES, 'UTF-8') . ', Portagee!'; } else{ if ($firstname == 'Jon' and $lastname == 'Spense') { $output = 'Welcome to our site, ' . htmlspecialchars($firstname, ENT_QUOTES, 'UTF-8') . ', bro!'; } } $output = 'Welcome to our site, ' . htmlspecialchars($firstname, ENT_QUOTES, 'UTF-8') . ' ' . htmlspecialchars($lastname, ENT_QUOTES, 'UTF-8') . '!'; ?> Hey everyone, i am currently working on a "contact us" script. I want the form to first allow the user which department they want to email. E.g. "Sales" and "Support" By changing this drop down box it will change which email the form is sent to. Im having trouble setting the PHP side of this script up to change the emails. Any help regarding this matter is much appreciated. HTML FORM: Code: [Select] <form name="contactForm" method="post" action="forms/contactUs.php"> <table width="350" border="0"> <tr> <td width="150" class="bold">Department:</td> <td width="200" align="left"> <select name="department" class="dropDown"> <option value="sales">Sales</option> <option value="support">Support</option> </select> </td> </tr> <tr> <td class="bold">Full Name:</td> <td> <input name="name" type="text" class="contactTextBox" /> </td> </tr> <tr> <td class="bold">Company:</td> <td> <input name="company" type="text" class="contactTextBox" /> </td> </tr> <tr> <td class="bold">Email:</td> <td> <input name="email" type="text" class="contactTextBox" /> </td> </tr> <tr> <td class="bold">Comments:</td> <td> <textarea name="com" id="com" cols="5" rows="5" class="contactTextArea" /></textarea> </td> </tr> <tr> <td> </td> <td align="right"> <input type="submit" class="button" value="Submit" /> <input type="reset" class="button" value="Reset" /> </td> </tr> </table> </form>PHP <?php $department = $_POST['department']; $confirm = "sales"; if(isset($_POST['email'])) { if($department == $confirm) { $email_to = "sales@pixemadesigns.com"; $email_subject = "Sales Question"; } else { $email_to = "support@pixemadesigns.com"; $email_subject = "Support Question"; } $fullName = $_POST['name']; $company = $_POST['company']; $email_from = $_POST['email']; $comments = $_POST['com']; $email_message = "Form details below.\n\n"; function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); } $email_message .= "Full Name: ".clean_string($fullName)."\n"; $email_message .= "Company: ".clean_string($company)."\n"; $email_message .= "Email: ".clean_string($email_from)."\n"; $email_message .= "Comments: ".clean_string($comments)."\n"; // create email headers $headers = 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); header("location: ../contactSubmit.html"); ?> <? } ?> Hi, can't get my head around this one! I have this code :- if (isset($_SESSION['cartid']) && !isset($_SESSION['lockedcard']) && isset($_POST['cartitem']) && isset($_POST['quantity']) && is_numeric($_POST['quantity'])) { if ($_POST['quantity'] > 0) {
Which I need to add an OR statement to : - (!isset($_SESSION['lockedpaypal']). if (isset($_SESSION['cartid']) && ($_SESSION['lockedpaypal'] != '1' || ['lockedcard'] != '1') && isset($_POST['cartitem']) && isset($_POST['quantity']) && is_numeric($_POST['quantity'])) { if ($_POST['quantity'] > 0) { Thanks! [About the code] Basically what I have is a web page that de-codes a complex XML document, and displays it as a table. This is working successfully. One of the columns in the tables displays a "rank" of an object as a number (0-9). This is working successfully. What I did was write a code that would translate that rank number into a specified text, depending what number it was. [The Code] (This is only the partial code with the problem in it, the entire code of the page is very extensive.) Code: [Select] $RankNum = "{$Member->Rank}"; // {$Member->Rank} successfully displays the rank number on it's own. Below 'should' translate that number into the name of the rank. if('$RankNum' == 0) { echo('test1');}; if('$RankNum' == 1) { echo('test2');}; if('$RankNum' == 2) { echo('test3');}; if('$RankNum' == 3) { echo('test4');}; if('$RankNum' == 4) { echo('test5');}; [The Problem] All this code keeps displaying "test1" for every value in the entire column, regardless if it equaled 1 or 2 or higher... I know this has to be some simple coding mistake, but I've been sitting here for an hour trying to figure out what I had done wrong. Thanks in advance :) When having different levels of directories, using relative paths will not work anymore, for example: controller - authentication File 1: include('../../model/header.php') model File 2: header.php view File 3. style.css The header.php file includes the css file with a relative path, but the problem is it includes it as follows: ../view/style.css When now the header.php file gets included into File 1 in the folder "authentication", then the css file will not be accessible anymore, for it to be accessible you would have to go two directories up. In this sense my question is, what would be the proper path structure for a folder structure with multiple levels? Should I rather use absolute paths, I am not so prone of absolute path. What if the folders changes a bit, or the domain changes, or the location changes? Say I have two areas of a website. 1 - root directory (index, sign up, sign in) 2 - folders (this would contain folders such as snippets, members, assets) Due to the nature of the folders, the links cannot be the same as they are on the pages in the root directory. Index page for example. So if I'm on members/dashboard.php, any a links linking to index.php, will have to have "../" in front of them. To solve the issue, my current set up is like this. But I understand it's not the most efficient way to do this. I was wondering if you can share your expertise for a better method. $currentPage = basename($_SERVER['PHP_SELF'], ".php"); <?php if($currentPage == 'index' || $currentPage == 'members') { ?> <!DOCTYPE HTML> <head> <meta charset="UTF-8"> <title></title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <link rel="shortcut icon" href="images/favicon.ico.png"> <link href="css/screen.css" media="screen" rel="stylesheet" /> </head> <body> <a href="index"> <img src="images/logo.PNG" alt="logo" /> </a> </body> <?php } else { ?> <!DOCTYPE HTML> <head> <meta charset="UTF-8"> <title></title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <link rel="shortcut icon" href="../images/favicon.ico.png"> <link href="../css/screen.css" media="screen" rel="stylesheet" /> </head> <body> <a href="../index"> <img src="../images/logo.PNG" alt="logo" /> </a> </body> <?php } else { ?>
Should this be the proper way of adding the getUsername() text in the query below: Code: [Select] mysql_query("UPDATE posts SET content = '$content', lastedit = ". getUsername() .":NOW() WHERE id = '$pid'") or die(mysql_error()); Im having trouble with this wondering if someone could help me out please if (isset($_POST['escape'])) { || if (isset($_POST['suicide'])) { its giving me a error on the || im writing it so that one or the other has to happend. is this the correct way to use this? That's right I'm pretty green when it comes to PHP. I googled it, but it looks like there are several ways to achieve this, wondering which is best.
elseif ($subcategory_id == 400)I want the code to include a number of subcategory_ids, 400, 450, 500, 760, etc. There isn't a range, so what would be the proper way to include multiple category_ids. Thank you Code: [Select] if (isset($select_category) || isset($most_liked)) { // ALL but NO OTHER if (((($select_category == 'All') || (!isset($select_category)))) && (!isset($most_liked))) { $query = "SELECT * FROM con, user WHERE con.user_id = user.user_id ORDER BY contribution_date DESC"; fetch_all ($dbc, $query); // CATEGORY but NOT most_liked } elseif (isset($select_category) && !isset($most_liked)) { $query = "SELECT * FROM con, user WHERE con.user_id = user.user_id AND category = '$select_category' ORDER BY contribution_date DESC"; fetch_all ($dbc, $query); // CATEGORY and MOST_LIKED } elseif (($select_category != 'All') && (isset($select_category) && isset($most_liked))) { $query = "SELECT * FROM con, user WHERE con.user_id = user.user_id AND category = '$select_category' ORDER BY likes DESC"; fetch_all ($dbc, $query); // ALL or NO CATEGORY but MOST LIKED } elseif ((($select_category == 'All') || (!isset($select_category))) && (isset($most_liked))) { $query = "SELECT * FROM con, user WHERE con.user_id = user.user_id ORDER BY likes DESC"; fetch_all ($dbc, $query); } } What I am basically trying to accomplish is, choose a category through a drop down list, select that category and then go through all the rows in the database and print the content out. As of now it is working for me, I am also using a pagination script to print out everything in a table. The problem I am having is that fetch_all function is also printing the query out together with the content. Any ideas why it does that? Did I use this function the right way? If you need more information let me know. $sql = "SELECT option_id, id FROM bets WHERE win_status = '1' AND updated_at BETWEEN '$today 13:00:00.000000' AND '$tmrw 08:00:00.000000'"; $result = mysqli_query($connt, $sql); foreach($result as $value) { $value[] = arary_multisort(); $oid = $value['option_id']; $gid = $value['id']; var_dump($value); //$gim = var_export($value); } foreach($result as $key => $value) { $info = array($value); } mysqli_close($connt); $fl = array($oid, $gid); print_r($fl);
array ( Either I can return 1 row and have the data sorted nicely or I can return an array but I can only seem to access the last array. Been stuck on this bit for atleast 2 hrs sadly. How can I rename the array? Some days I might have 100 results. Today we have two winners xP I really need to ctrl+z sublime cuz I tried what feels like everything. Ancy to move to the next part of this code MATH if you can kindly assist. Yall have been extremely helpful in my last two posts 2/2 going on 3. Is there a place I can properly contribute lite silver :3 Hello everyone, I've recently asked a question about forms and Requinix mentioned PRG method of processing forms. The PRG idea solves my refresh and back button document expired problems but i notice something new: when i refresh a page or use the browser back button - then return to the PRG process - repeat a refresh or back button action - i notice that i can traverse the cache history as many times as my prg approach redirects me. I feel like i am not implementing this PRG method correctly, or is this correct? Here is the form process if it helps solve the problem: i have a login form which contains a CSRF token. when i submit the form i specify an action as /prg/ which submits the data to index.php in the prg folder. After processing the data, prg index.php redirects to the root (because you are logged in). One problem is that i have a logo on the login page that allows you to return to the root (localhost index page). When the form is not submitted or it contaiuns incorrect login data or the logo is clicked to return to homepage, then the history seems to repeat itself. I've read that people recommend to use a header 303 See Other but the result is the same. Basiclly, if i am implementing a prg correctly, then the question becomes how can i instruct a browser to ignore the redirect as if the cache contains only the index page? i cannot find prg examples that involve a csrf token and other links on the protected page (prg/index.php protected because you need a form submission with a csrf token and it only processes data then redirects.) I don't see this happening in professional sites like Google or Microsoft etc. what am i doing wrong? Hi Guys,
Total PHP Noob here. I’ve run into a brick-wall and would appreciate some words of wisdom. I can do this with a browser: http://86.60.161.24 // will echo hello World I can’t do this with my server: <?php $url = 'http://86.60.161.24'; $contents = file_get_contents($url); echo ($contents); ?> It looks like the server-side HTTP -request never “touches” my Arduino-chip. No network activity detected. Obviously there is going to be a lot more data transfer happening but I need to solve this issue first. Is there anything I can do to make this work? Any and all input greatly appreciated. Cheers!!
Hi guys, I'm starting to get back into coding for a hobby and wondering is there a better way of doing these php and mysql calls? they all work but not sure if it was the efficent way or is there others that everyone else uses?
//connection for user details lookup
while($row2 = $result2->fetch_assoc()) {
//connection for role access against business lookup
while($row3 = $result3->fetch_assoc()) { Hi, I'm pretty new to php and need a bit of basic help. I have a header and footer include file in a "views" folder. The header itself has a function that's included from another directory. Now when I try to include the header in by index.php in the root it throws and error saying it can't find my function include. Obviously the include directory is relative to the file it's included in. So, what's the trick to fixing this problem? And what's the lesson for future projects? Thanx in advance. Hello everyone. First post here. very new to php and html. Im working on my uncles website which is a fabric store. I created a mysql database and a search to use. Im trying to make this a fulltext search because right now you have to match the pattern name exactly to get any results! And if somebody searches for the pattern name and the color they will get no results! In fact, if there is more than one search term, there is no results. -This is the first part where it counts so the pagination can be built- $sql = "SELECT COUNT(*) FROM rapatterns WHERE Pattern= '$keyword' OR Color= '$keyword' OR Fabric_Use= '$keyword'"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); -here is the query to get results- $sql = "SELECT * FROM rapatterns WHERE Pattern= '$keyword' OR Color= '$keyword' OR Fabric_Use= '$keyword' LIMIT $offset, $rowsperpage"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); Ive looked into full text searching, and ive created a fulltext index on the three columns being searched here. The problem im having is when I try to change the queries to fulltext searches I get syntax errors. -this is what i was trying to do- -this is the first one that counts for pagination- $sql = "SELECT COUNT(*) FROM rapatterns WHERE MATCH(Pattern,Color,Fabric_Use) AGAINST ('$keyword') LIMIT $offset, $rowsperpage"; -here is the second one to get results- $sql = "SELECT * FROM rapatterns WHERE MATCH(Pattern,Color,Fabric_Use) AGAINST ('$keyword') LIMIT $offset, $rowsperpage"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); Im wondering if I can get a little help with the syntax or if what im trying to do wont work at all. Go easy on me. I am extremely new to any of this. This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=345920.0 I built a website that has multiple users accessing it at once, there is a problem with the sessions. People are getting directed to a logged out page. I know why this is because I don't thoroughly understand how to use sessions.
I have picked up about storing in places other than /tmp , I'm concerned about storage and not carrying it from one page to the next
So when a person logs in, then they hit back on their browser or exit it (for a phone) and go back to it, they should still be logged in. That doesn't happen, they are usually logged out.
Also there is a weird anomaly. When I use the website on my device (phone) I don't have a problem of session value getting lost and the website exists on a server / computer that is not this phone, so why does my friend have problems with sessions but not me?
This is my general session code, it is garbage
<?php ob_start(); session_start(); if( !isset($_SESSION['last_access']) || (time() - $_SESSION['last_access']) > 60 ) $_SESSION['last_access'] = time(); session_save_path('/home/admin2/public_html/sesh'); ini_set('session.gc_probability', 1); $userrname = $_SESSION["user"]; $_SESSOIN["user"]=$userrname; if (empty($userrname)){ header("Location: "); } ?>I'd appreciate any help. Thank you. |