PHP - Logic Question With A Form
I want my PHP code to display and handle a form.
If the form hasn't been submitted it needs to display the form. If the form has been submitted but the data couldn't be validated then I want to display the same form (with the user's data intact). If the form has been submitted and the data was validated then it handles the form and prints a message. The problem I seem to be having is that I have nested conditionals that both need to execute the same code. I cant seem to wrap my head around it. Similar TutorialsHello guys, I have a question about the logic of OR (||) and && I have a form and on the form is asks for hair color Code: [Select] <div class="hcenter"><div class="box3">Hair color</div></div> <div class="box2"><input type="radio" name="hair" value="Black" />Black<br /> <input type="radio" name="hair" value="Brunette" />Brunette<br /> <input type="radio" name="hair" value="Blonde" />Blonde<br /> <input type="radio" name="hair" value="Red" />Red<br /></div> I grab the post var like this $hair = $_POST['hair']; // I actually have it filtered but you get the point I created this function Code: [Select] function check_Haircolor($hair){ if (isset($hair) && $hair != 'Brunette' || $hair != 'Black' || $hair != 'Red' || $hair != 'Blonde' ){ Do something here } } But it would not work correctly.. I kept doing the "Do something here...." so I tried the && and it worked (Se below) as expected. I would have bet that the or (||) would have been the correct code.. Code: [Select] function check_Haircolor($hair){ if (isset($hair) && $hair != 'Brunette' && $hair != 'Black' && $hair != 'Red' && $hair != 'Blonde' ){ Do something here } } Why did the && word and not the || Thanks, Dan Hello, Is this a sound explanation of require and include.. Lets say i have "X" application with an index.php file. in a folder on my domain like so: www.xxx.com/Application X folder/index.php. // the index.php calls to multiple files with-in the "Application X folder" and database. What if i move the index.php to another location all together like so: http://www.xxx.com/notXsubfolder1/notXsubfolder2/notXsubfolder3/index.php //the X application index file.. and then edit the require and include links in the index.php file to paths like this (just example might not be accurate): require_once '../../../../application X Folder/include/required_file.php'; My question:?? What i want to know is: if the required_file.php has includes of its own, will it take the includes that it requires from its original folder where the Required_file.php is located? or will its paths change the the new index.php location?? . I have read around and can't seem to find the right coding for what I need on this forum and some other other forums. I have a contact form (as listed below) and I need 2 locations (Print Name and Title) fields to auto-populate on a separate form (can be a doc, pdf, etc. any form of document which is easiest) and this form can be totally back end and the individual using the form never is going to see the form. It's going on a contract form, that we would like to auto-populate. Also is there a simple attachment code so individuals can attach documents to the code? <p style: align="center"><form action="mailtest.php" method="POST"> <?php $ipi = getenv("REMOTE_ADDR"); $httprefi = getenv ("HTTP_REFERER"); $httpagenti = getenv ("HTTP_USER_AGENT"); ?> <input type="hidden" name="ip" value="<?php echo $ipi ?>" /> <input type="hidden" name="httpref" value="<?php echo $httprefi ?>" /> <input type="hidden" name="httpagent" value="<?php echo $httpagenti ?>" /> <div align="center"> <p class="style1">Name</p> <input type="text" name="name"> <p class="style1">Address</p> <input type="text" name="address"> <p class="style1">Email</p> <input type="text" name="email"> <p class="style1">Phone</p> <input type="text" name="phone"> <p class="style1">Debtor</p> <input type="text" name="debtor"> <p class="style1">Debtor Address</p> <input type="text" name="debtora"> <br /> <br /> <a href="authoforms.php" target="_blank" style="color:#ffcb00" vlink="#ffcb00">Click here to view Assignment Agreement and Contract Agreement</a> <p class="style1"><input type='checkbox' name='chk' value='I Have read and Agree to the terms.'> I have read and agree to the Assignment and Contract Agreement <br></p> <p class="style1">Print Name</p> <input type="text" name="pname"> <p class="style1">Title</p> <input type="text" name="title"> <p class="style1">I hear by agree that the information I have provided is true, accurate and the information I am submitting is <br /> not fraudulent. Please click the agree button that you adhere to Commercial Recovery Authority Inc.'s terms:</p> <select name="agree" size="1"> <option value="Agree">Agree</option> <option value="Disagree">Disagree</option> </select> <br /> <br /> <p class="style1">Employee ID:</p> <input type="text" name="employee"> <br /> <input type="submit" value="Send"><input type="reset" value="Clear"> </div> </form> </p> The mailtest php is this ?php $ip = $_POST['ip']; $httpref = $_POST['httpref']; $httpagent = $_POST['httpagent']; $name = $_POST['name']; $address = $_POST['address']; $email = $_POST['email']; $phone = $_POST['phone']; $debtor = $_POST['debtor']; $debtora = $_POST['debtora']; $value = $_POST['chk']; $pname = $_POST['pname']; $title = $_POST['title']; $agree = $_POST['agree']; $employee = $_POST['employee']; $formcontent=" From: $name \n Address: $address \n Email: $email \n Phone: $phone \n Debtor: $debtor \n Debtor's Address: $debtora \n 'Client' has read Assignment and Contract Agreement: $value \n Print Name: $pname \n Title: $title \n I hear by agree that the information I have provided is true, accurate and the information I am submitting is not fraudulent. Please click the agree button that you adhere to Commercial Recovery Authority Inc.'s terms: $agree \n \n Employee ID: $employee \n IP: $ip"; $recipient = "mail@crapower.com"; $subject = "Online Authorization Form 33.3%"; $mailheader = "From: $email \r\n"; mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); echo "Thank You!" . " -" . "<a href='index.php' style='text-decoration:none;color:#ffcb00;'> Return Home</a>"; $ip = $_POST['visitoraddress'] ?> Logic problem: Current directory listing at: http://www.nmlta.org...member_list.php shows the format I need. The only way I have previously been able to accomplish that format is by running four separate queries in a loop, which I understand is not good. Trying to simplify this, I need to explain my data. There are companies, and contact people at those companies, and some companies have branches, and most branches have contact people at them.
There are four tables: company, co_contact, branch, br_contact. The company, co_contact and branch tables all have a field called “company_id” to match the ones that go together, and the branch table also has a “branch_id” field to match with the people in the br_contact table.
I am successful with running separate JOIN queries for company/co_contact matching on “company_id”, and for branch/br_contact matching on “branch_id”, and have successful processes for listing the data properly.
My problem is I can’t find the logic to run them all in one query or loop that will produce the desired output I’m getting with my current four-query mess. The process should go like this:
List company1 info
List all contacts at company1
List branch1 connected to company1 (if applicable)
List all contacts at branch1 of company1
List branch2 connected to company1 (if applicable)
List all contacts at branch2 of company1
Etc. until all branches are listed for company1
Start over with company2…
Here is the code for my first attempt:
<?php function listCompany($row) { echo $row['comp_name'],"<br />"; if (!empty($row['comp_uw'])) { echo $row['comp_uw'],"<br />";} echo "</b>",$row['comp_street'],"<br />"; if (!empty($row['comp_pobox'])) { echo $row['comp_pobox'],"<br />";} echo $row['comp_csz'],"<br />"; echo $row['comp_ph'],"   Fax: ",$row['comp_fx'],"<br />"; if (!empty($row['comp_tfree'])) { echo "Toll Free: ",$row['comp_tfree'],"<br />";} if (!empty($row['comp_email'])) { echo "Email: <a href='mailto:",$row['comp_email'],"'>",$row['comp_email'],"</a><br />";} if (!empty($row['comp_web'])) { echo "<a href='http://",$row['comp_web'],"' target='_blank'>",$row['comp_web'],"</a><br />";} echo "</p>"; } function listBranch($row2) { if (!empty($row2['br_name'])) { echo "<p>     <b>",$row2['br_name'],"</b><br />";} echo "     ",$row2['br_street'],"<br />"; echo "     ",$row2['br_csz'],"<br />"; echo "     ",$row2['br_ph'],"   ",$row2['br_fx'],"<br /></p>"; } function listContact($row) { if (!empty($row['cont_name'])) { echo "<p>     <b>",$row['cont_name'],"</b>, ",$row['cont_title'],"<br />";} if (!empty($row['cont_email'])) { echo "     Email: <a href='mailto:",$row['cont_email'],"'>",$row['cont_email'],"</a><br />";} echo "</p>"; } function listBranchContact($row2) { if (!empty($row2['cont_name'])) { echo "<p>          <b>",$row2['cont_name'],"</b>, ",$row2['cont_title'],"<br />";} if (!empty($row2['cont_email'])) { echo "          Email: <a href='mailto:",$row2['cont_email'],"'>",$row2['cont_email'],"</a><br />";} echo "</p>"; } // Connection to DB $mysqli = new mysqli("localhost", "nmlta_admin", "trooper", "nmlta_agents"); if($mysqli->connect_errno > 0){ die('Unable to connect to database [' . $db->connect_error . ']'); } // Retrieve all the data from the "company" table for County and join matching people from the "co_contact" table $query = "SELECT * FROM company LEFT JOIN co_contact ON company.company_id = co_contact.company_id WHERE comp_county = 'BERNALILLO' ORDER BY company.comp_name, co_contact.cont_rank"; $result = $mysqli->query($query) or die($mysqli->error.__LINE__); // Initialize variable $lastCompany = ''; // Start building the table to show results echo "<table border='1' cellpadding='10' cellspacing='0' bgcolor='#f0f0f0' style='margin-left:100px; margin-bottom:20px'>"; // Begin the Company "while" loop for rows in the $result while($row = $result->fetch_assoc()) { // Company - Loop 1 // Check if this is a different company than the last one if ($lastCompany != $row['company_id']) { // New Company Check - Loop 2 // If this is a different company - change the $lastCompany variable $lastCompany = $row['company_id']; echo "<tr><td><p><b>"; // List the company info only if it is not the $lastCompany listCompany($row); } // End New Company Check - Loop 2 // List all Contacts in the Company listContact($row); if ($row[next($row['company_id'] != $lastCompany)]) { // Start Branch // Retrieve all the data from the "branch" table for County and join matching people from the "br_contact" table $query2 = "SELECT * FROM branch LEFT JOIN br_contact ON branch.branch_id = br_contact.branch_id WHERE company_id = '".$row['company_id']."' ORDER BY branch.comp_name, branch.br_street, br_contact.cont_rank"; $result2 = $mysqli->query($query2) or die($mysqli->error.__LINE__); // Initialize variable $lastBranch = 'xxx'; //Initialize $lastBranch variable // Begin the Branch "while" loop for rows in the $result2 while($row2 = $result2->fetch_assoc()) { // Branch - Loop 1 // Check if this is a different branch than the last one if ($lastBranch != $row2['branch_id']) { // New Branch Check - Loop 2 // If this is a different branch - change the $lastBranch variable $lastBranch = $row2['branch_id']; echo "<tr><td>"; // List the branch info only if it is not the $lastBranch listBranch($row2); } // End New Branch Check - Loop 2 // List all Contacts in the Branch listBranchContact($row2); } // End Branch - Loop 1 } } // End Company - Loop 1 echo "</td></tr>"; // Free result set mysqli_free_result($result); echo "</table>"; mysqli_close($mysqli); ?>My first thought was to insert the "if ($row[next($row['company_id'] != $lastCompany)]) {" qualifier after listing the contact for the company being processed, that way when I know a new company is on the next row, I can pause and run my second query to find any applicable branches that match the current company_id. The syntax must be wrong the way I have it, because I get an error with this, saying: "Fatal error: Only variables can be passed by reference in..." referencing that call in my code. I don't know if there is a syntax change that would make this work, or not. I have thought about, and tried different ways to run a query using JOIN on all four of my tables, but the resulting rows do not correspond with the order in which I need to process them, if that makes sense. I am not opposed to any suggestions that will make this work - I just can't seem to think it through and find the correct solution, if there is one. The difficulty seems to me to be that the process of listing company/contact info needs to know when it has reached the last row containing a contact tied to the company, so that the branch routine can be processed for the same company. Any help or suggestions would be appreciated. Thanks! I want to ask the user questions by using a form. I have a text field where the user inputs either 1 or 2 and then they press submit. I can get this to work but I need to keep asking them questions based off there last answer to the previus question.
I am making a game where you start with a number ex 5 and then you either choose to take away 1 or two from that number. so we take away 2 now the number is 3 and then the computer has his go using the same number. He chooses to take away 1 which makes the number 2. Now we take away 2 and win the game for being the first one to get the number down to 0. Its a very simple game that im trying to do just to brush up on my php skills.
my code so far....
<p> please enter a number to begin the subtraction game</p> <form name="submit1" method="post"> <input type="text" name="startingNumber"> <input type="submit" name='submit1'> </form> <?php if (!empty($_POST['startingNumber'])) {?> <p>your starting number is: <?php echo $_POST['startingNumber']?></p> <?php while(!$_POST['startingNumber'] == 0){?> <p> Would you like to minus one or two from <?php echo $_POST['startingNumber']; ?></p> <form name="submit2" method="post"> <input type="text" name="oneOrTwo"> <input type="submit" name='submit2'> </form> <?php } }?>As you can see i am no where near close to getting this right. Im thinking i have to use a while loop to keep asking the question minus 1 or 2 until they reach 0. Inside this while loop im thinking i need something like a waituntil user has clicked submit. In fact i have written the same game in c++ so if it helps here is that. (it works just how i want it too) the problem im having is that in c++ you can use cin to get a input from the user and it waits until the user types in a value but im struggling to find anything like that in php. Any help would be greatly appreciated thank you. #include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]) { int number, oneOrTwo, remainder; cout << "please enter a number to begin the subtraction game"; cin >> number; while (number != 0){ cout <<"your turn, subtract 1 or 2 from " << number << endl; cin >> oneOrTwo; if (oneOrTwo == 1 || oneOrTwo == 2){ number = number - oneOrTwo; }else{ cout << "sorry you have entered a incorrect number. Please enter either 1 or 2" << endl; continue; } if (number == 0){ cout << "congratulations! you won the game"; break; } remainder = number % 3; if (remainder % 3 == 0){ remainder = 2; } cout << "now my turn im going to subtract " << remainder << " from " << number << endl; number = number - remainder; if (number == 0){ cout << "sorry the computer won this time"; } } system("PAUSE"); return EXIT_SUCCESS; } Edited by yacobm8, 16 May 2014 - 12:14 AM. Hi all, Its been a while since I looked at PHP and I have forgotten some basics What I am trying to achieve is display category names, sub categories and results into a list Code: [Select] <ul id="nav"> <li><a href="#">Main Cat</a> <ul> <li><a href="#">Sub Cat 1</a> <ul> <li><a href="#">result</a></li> <li><a href="#">result</a></li> </ul> </li> <li><a href="#">Sub Cat 2</a> <ul> <li><a href="#">result</a></li> <li><a href="#">result</a></li> </ul> </ul> </li> What would be the best way to organise my database? Have everything in one entry like: main_id / sub_id / listing_id / listing_name or separate them into a table for cats, one for sub cats and what parent it belongs to, then a table for the listings linking to the sub cat it belongs to? I have confused myself no end on how then to display the results, so any help with would be gratefully received! Thanks Dave I have a file sharing script, where each file has a certain number of points. I need to subtract a set number of points from the total. I'm unsure about the logic of it. This is how I total the number of points: Code: [Select] <?php $fq = "SELECT * FROM `files` WHERE owner='$username' AND active=1"; $fw = $sql->query($fq); $reward = 0; while($fr = $fw->fetch_assoc()){ $reward = $fr['points'] + $reward; }?> I'm thinking I should use a loop, while a the number to subtract is greater than or equal than 0. Can anyone help? I am trying to understand PHP While Loops. For example. $info=mysql_fetch_array($query); will create an array of a mysql query. how does while($info=mysql_fetch_array($query) { echo $info['1']; } ensure that each element of the array is echoed. It seems that $info is a one time statement that grabs an array, how does adding While make it capable of being extended into rows? To me this says While this is true, do this. But if it is true once, how does PHP know when to stop? i have two multi-dimensional arrays that i'd like to manipulate to check a few things. Their structures are different and i'm giving myself headaches trying to think through this. I have a $sums array which has information on a product in a purchase order. The second array consists of items(products) that are going to update the purchase order. So the first array key of $sums correlates with the "order" of the $items array. I'd like to write a function that: 1. Makes sure the first array key of $sums exists as an "order" value in the $items array. 2. Makes sure the $items price is greater than the $sums price Code: [Select] <?php $sums['23']['collected']['price'] = 30; $sums['73']['collected']['price'] = 60; $sums['89']['collected']['price'] = 90; $items['abc123']['order'] = '23'; $items['abc123']['price'] = 14; $items['321cba']['order'] = '73'; $items['321cba']['price'] = 79; function check_items($sums,$items) { $error = ""; //Makes sure the first array key of $sums exists as "order" value in the $items array. //If not -> $error = "Item #".$key." is not found in the items array."; //where $key is either the first array key of $sums or the "order" value in $items because they are the same thing //if found in $sums if($items[$hash]['price'] < $sums[$items[$hash]['collected']['price'] ) { $error = "Item #".$items[$hash]['order']."'s price must not be lower than ".$sums[$items[$hash]['order']]['collected']['price']; } return $error; } // $sums['23'] would cause an error because its price of 14 is less than 30 // $sums['73'] would pass because it exists in $items and its price of 79 is greater than the $sums price of 60. // $sums['89'] would cause an error because there is no $item corresponding to it ?> I just don't know where to put the foreach loops or where to even start really :/ I make a query where I fetch som individuals and group them by class and count the rows. I make a for statement and in that statement I make a new query where I fetch all individuals in each class and sort them by id. Each member in each class should be printed into a file, limited by 15, if there is more than 15 the rest should be printed to the next file. My logic is a little confusing to me... Code: [Select] $queryorder = "SELECT * FROM mytable GROUP BY class ORDER BY cat_order"; count $rows1... for ($ii = 0; $ii < $rows1; $ii++) { $query = "SELECT * FROM mytable WHERE class = '". $rows1[$ii]['class'] . "' ORDER BY id"; $rows2 $count = 1; $sid_nr = 1; $list_nr = 1; for ($iii = 0; $iii < $rows2; $iii++) { if($count == 1) { createnewfile $ring = $rows2[$iii]['ring']; } for($count_i = 1; $count_i < 16; $count_i++): if($rows2[$iii]['C'] == 1){$rows2[$iii]['C'] = 'C';}else{$rows2[$iii]['C'] = '';} if($rows2[$iii]['S'] == 1){$rows2[$iii]['S'] = 'S';}else{$rows2[$iii]['S'] = '';} if($count_i == $count) { variabel1='VAR1'.$count_i, $rows2[$iii]['nr']); variabel2='CS'.$count_i, $rows2[$iii]['C'] . $rows2[$iii]['S']); variabel3='NAME'.$count_i, $rows2[$iii]['id_nr'] . ' ' . $rows2[$iii]['name']); } endfor; $count++; if($count == 15) { $filename = somefilename; $myFile = $resultiddir.DS.$filename; closefile $count = 1; $sid_nr++; } if($count == $rows2 { $filename = somefilename; $myFile = $resultiddir.DS.$filename; closefile $count = 1; $sid_nr = 1; } } } Some of it is pseudocode but the idea is the important thing:) So I have this killer script I wrote for article management across multiple sites. I am trying to make a drip feed so you can set up a bunch of articles for one site to drip out over x amount of days. Then you could do that for your next site etc... so you do not need to manage all of your 20 blogs/sites a day. So, I am thinking I have all these variables in a table: Code: [Select] Table 1 Article - URL for article - Title - Keywords - Anchor Text - URL link - Category - Site to post to ID Code: [Select] Table 2... URL - Date Posted - Drip Feed (maybe include category here because in table 1 it will repeat category for every row of the same url) Then I make a script that runs on a cron job every 2-4 hrs... Not sure the best way to make the script and also not sure the best way to post this info to different sites... ideally id like to be able to post to joomla, wordpress, blogspots, etc... basically many different kinds of sites. Any suggestions would be appreciated... no need for you to write the code I can do that, just need a plan. Hey there. My first post here! Now, I've got this problem trying to solve some logic problem in a foreach loop, while it sounds simple - and I know I've done it before, I can't for the life of me remember how, or re-invent the method of which I did it. What I'm trying to do is to read an external XML file, break it down, and while looping the important fields which holds the data I want to echo, I want to check if a certain condition is met, i.e. if there is a <character ...> child that has classId="1" just to create an example. The problem is, doing this inside the loop will, if there are 100 <character ..> childs, loop the condition 100 times, breaking or halting the if statement inside the loop will halt/break the loop itself. Just checking like this: if($character['classId'] == 1) { .. } else { .. } Won't work either as that checks if all the character fields contain it without having the intended effect. I'm wondering if any of you guys have any idea how to slove this, been sitting at it for a few hours and I can't for the life of me remember how I did it the first time. I'll include the code I've got so far, removing the checks that didn't work. Any help would be greatly appreciated! // Create a basic grabber function.. function grabArmory($url) { // cURL Settings $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute! $data = curl_exec($ch); // .. And close! curl_close($ch); // Then give us the dataz... return $data; } // The URL to grab. //$url = 'http://eu.wowarmory.com/guild-info.xml?r=Neptulon&gn=Ascendance'; $url = 'http://eu.wowarmory.com/guild-info.xml?r=Doomhammer&gn=rise+against'; // Grab dat data and cache it! $data = grabArmory($url); // Then try and parse it $xml = new SimpleXMLElement($data); // Fetch member count and store it. $memberCount = $xml->guildInfo->guild->members['memberCount']; // Loop all the Guild's members foreach($xml->guildInfo->guild->members->character as $member) { /* Rank 0: Guildmaster 1: Officer 2: Raider 3: Member 4: Trial 5: Alt 6: Community */ // Sort out their Ranking first and foremost! if($member['rank'] == 0) { $member['rank'] = 'Guildmaster'; } elseif($member['rank'] == 1) { $member['rank'] = 'Officer'; } elseif($member['rank'] == 2) { $member['rank'] = 'Raider'; } elseif($member['rank'] == 3) { $member['rank'] = 'Member'; } elseif($member['rank'] == 4) { $member['rank'] = 'Trialist'; } elseif($member['rank'] == 5) { $member['rank'] = 'Alt'; } elseif($member['rank'] == 6) { $member['rank'] = 'Community'; } else { $member['rank'] == 'Unknown'; } /* Sort Genders, Races and Classes by their ID's. 0 = Male 1 = Female 1: Human 1: Warrior 2: Orc 2: Paladin 3: Dwarf 3: Hunter 4: Nightelf 4: Rogue 5: Undead 5: Priest 6: Tauren 6: Death Knight 7: Gnome 7: Shaman 8: Troll 8: Mage 10: Blood Elf 9: Warlock 11: Draenei 11: Druid */ if($member['classId'] == 1) { // Warriors } elseif($member['classId'] == 2) { // Paladins } elseif($member['classId'] == 3) { // Hunters } elseif($member['classId'] == 4) { // Rogues } elseif($member['classId'] == 5) { // Priests } elseif($member['classId'] == 6) { // Death Knights } elseif($member['classId'] == 7) { // Shamans } elseif($member['classId'] == 8) { // Mages } elseif($member['classId'] == 9) { // Warlocks{ } else { // Druids } } This is what I want:
If comparisonTimeH isn't zero, I want it to check if comparisonTimeH is zero, and comparisonTimeM is larger than or equal to 2. If so, I want it to pass and run the script.
This is what I have, and it's not right. It runs the else statement, echo test 2.
if ($comparisonTimeH != 0 || $comparisonTimeH = 0 AND $comparisonTimeM >= 1) { echo "test"; } else { echo "test2"; } echo "<br />" . $comparisonTimeH . " " . $comparisonTimeM;My last echo, the one outside of the if statements - it returns 0 and 12. Thus, both conditions that I'm trying to get, are true. My if's logic is clearly wrong, and I can't figure out what operators to use. If I change the AND to &&, it breaks and my final echo doesn't return comparisonTimeH (it's blank). Please teach me, thanks! Edited by icor1031, 17 September 2014 - 07:48 PM. Hello, I'm trying to get code to work along the following logic (or something similar if this logic isn't PHP-friendly). If a user inputs a URL with the http, I want the url left alone. If the user inputs the URL starting with www, I want http:// added to the beginning. If the user does anything else (in other words uses a relative link), I want the beginning of my url to be added on (because then I later check for it to open the website in a new window or not). Code: [Select] if (strpos($url, "http") == 0) { $url = $url; } else if (strpos($url, "www") == 0) { $url = "http://".$url; } else { $url = "http://www.mywebsite.com/".$url; }; Any suggestions? Hi All, I'm trying to understand the logic behind this bit of code I found. I (think I) get that it takes an argument which in this case is a number, an checks to see if the array isset, then uses a while loop to loop through the possible values taking each value and placing it into another function which performs some task. What I'm really confused about is how the code is using unset, If I'm correct it's unsetting the incremented value which is the value that should be used in the next iteration, now I know this is not the case, but I don't understand why this is working. I have included the code in the topic and I also wrote a small piece of code to mirror this so I could play around with it in hopes of understanding the logic but it gives me a syntax error in my IDE when I try to unset the incremented value. I know this is probably something really stupid so be kind. <?php define("NUM_0", 0); define("NUM_1", 1); define("NUM_2", 2); define("NUM_3", 3); define("NUM_4", 4); function function_1($position) { static $positions = array(NUM_0, NUM_1, NUM_2, NUM_3, NUM_4,), $index = 0; if (isset($positions[$index])) { while ($position >= $index) { $current_position = $positions[$index]; unset($positions[$index++]); function_2($current_position); } } } function function_2($position) { switch ($position) { case 0: echo '$position equals 0 <br />'; break; case 1: echo '$position equals 1 <br />'; break; case 2: echo '$position equals 2 <br />'; break; case 3: echo '$position equals 3 <br />'; break; case 4: echo '$position equals 4 <br />'; break; } } function_1(NUM_4); [b] [u]output![/u] $position equals 0 $position equals 1 $position equals 2 $position equals 3 $position equals 4 [/b] function test() { static $var_1; $var_1 = 10; if (isset($var_1)) { while ($var_1 >= 0) { $var_2 = $var_1; unset ($var_1++); // syntax error on this line. echo $var_2; } } } test(); ?> I'm just trying to see if the order of my logic is correct or if there's something I can do differently. I'm also curious to know at what point I should get the 2 passwords that exists in the database for the user. These are two different passwords. Code: [Select] function login_submit() { $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean'); $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean'); $this->form_validation->set_rules('remember', 'Remember me', 'integer'); $user_id = $this->users->get_user_id_by_username($this->input->post('username')); if ($user_id !== 0) { if ($this->kow_auth->is_max_login_attempts_exceeded($user_id)) { echo json_encode(array('error' => 'yes', 'message' => 'Your account is currently locked, we appologize for the inconvienence. You must wait 10 minutes before you can login again!')); } else { $user_status = $this->users->get_user_status($user_id); if ($user_status == 1) { echo json_encode(array('error' => 'yes', 'message' => 'Sorry you must verify your account before logging in!')); } elseif ($user_status == 3) { echo json_encode(array('error' => 'yes', 'message' => 'Your account has been suspended!')); } elseif ($user_status == 4) { echo json_encode(array('error' => 'yes', 'message' => 'Your account is currently banned!')); } elseif ($user_status == 5) { echo json_encode(array('error' => 'yes', 'message' => 'Your account has been deleted!')); } else { if ($this->form_validation->run()) { if ($this->kow_auth->login($this->form_validation->set_value('username'), $this->form_validation->set_value('password'), $this->form_validation->set_value('remember'))) { redirect(''); } else { echo json_encode(array('error' => 'yes', 'message' => 'Incorrect username and password combination!')); } } } } } else { echo json_encode(array('error' => 'yes', 'message' => 'Incorrect username and password combination!')); } } Hi Guys, I'm sure my logic is off somewhere in my code, basicaly i resize an uploaded image and move to it's location depending on whether it came from the US or UK site: Resize Function: function resize_image($uploadDirectory, $newFileName, $us = false) { $original_image = $uploadDirectory; $ext = substr($original_image, strrpos($original_image, '.') + 1); $canvas_width = 65; $canvas_height = 65; $canvas = imagecreatetruecolor($canvas_width, $canvas_height); $white_background = imagecolorallocate($canvas, 255, 255, 255); imagefill($canvas, 0, 0, $white_background); list($image_width, $image_height) = getimagesize($uploadDirectory); $ratio = $image_width / $image_height; if ($ratio > 1) { $new_image_width = 65; $new_image_height = 65 / $ratio; } //$ratio > 1 else { $new_image_width = (float) 65 * $ratio; $new_image_height = 65; } if ($ext == "jpg") { $original_image = imagecreatefromjpeg($original_image); } //$ext == "jpg" if ($ext == "gif") { $original_image = imagecreatefromgif($original_image); } //$ext == "gif" imagecopyresampled($canvas, $original_image, 0, 0, 0, 0, $new_image_width, $new_image_height, $image_width, $image_height); $new_thumbnail_name = "thumb-$newFileName"; if ($ext == "jpg") { if ($us) { imagejpeg($canvas, "../../site.com/imgProducts/img-th/$new_thumbnail_name", 100); return ("$new_thumbnail_name"); } else { imagejpeg($canvas, "../imgProducts/img-th/$new_thumbnail_name", 100); return ("$new_thumbnail_name"); } } //$ext == "jpg" if ($ext == "gif") { if ($us) { imagegif($canvas, "../../first-site.com/imgProducts/img-th/$new_thumbnail_name", 100); return ("$new_thumbnail_name"); } else { imagegif($canvas, "../imgProducts/img-th/$new_thumbnail_name", 100); return ("$new_thumbnail_name"); } } //$ext == "gif" imagedestroy($original_image); imagedestroy($canvas); } Upload Code: <?php if (isset($_POST['submit-add-product'])) { $productNM = ucwords($_POST['txt-product-name']); $productDS = escape_data($_POST['txt-product-description'], 1); $productPM = $_POST['txt-product-p-medicine']; $productCT = $_POST['txt-product-category']; $productPR = $_POST['txt-product-price']; $productST = $_POST['txtSite']; $fileName = $_FILES['txt-product-image']['name']; $fileTemp = $_FILES['txt-product-image']['tmp_name']; $fileType = $_FILES['txt-product-image']['type']; $fileSize = $_FILES['txt-product-image']['size']; /*if (!empty($_FILES['txt-product-image-2']['name'])) { $fileName2nd = $_FILES['txt-product-image-2']['name']; $fileTemp2nd = $_FILES['txt-product-image-2']['tmp_name']; $fileType2nd = $_FILES['txt-product-image-2']['type']; $fileSize2nd = $_FILES['txt-product-image-2']['size']; $fileExtension = substr(strrchr($fileName2nd, '.'), 0); $fileExtension = strtolower($fileExtension); $replacedName2nd = str_replace(" ", "-", $productNM . "-2nd"); $newFileName2nd = "$replacedName2nd-" . time() . "$fileExtension"; $uploadDirectory2nd = "../imgProducts/img-fs/$newFileName2nd"; $generate2ndImage = true; } //!empty($_FILES['txt-product-image-2']['name']) if (empty($productNM)) { print "<p class=\"fcp-message-error\">You never entered a product name.</p>"; } //empty($productNM) if (empty($productDS)) { print "<p class=\"fcp-message-error\">You never entered a product description.</p>"; } //empty($productDS) if (empty($productPR)) { print "<p class=\"fcp-message-error\">You never entered a product price.</p>"; } //empty($productPR) if (empty($fileSize)) { print "<p class=\"fcp-message-error\">You never entered a product image.</p>"; } //empty($fileSize) if (!isImageFile($fileType)) { print "<p class=\"fcp-message-error\">The file you uploaded doesn't seem to be an image.</p>"; } //!isImageFile($fileType)*/ $fileExtension = substr(strrchr($fileName, '.'), 0); $fileExtension = strtolower($fileExtension); $replacedName = str_replace(" ", "-", $productNM); $newFileName = "$replacedName-" . time() . "$fileExtension"; $uploadDirectory = "../imgProducts/img-fs/$newFileName"; // US // if ($productST == "US") { $uploadDirectory = "../../first-choice-pharmacy.com/imgProducts/img-fs/$newFileName"; //move_uploaded_file($fileTemp, $uploadDirectory2nd); if (move_uploaded_file($fileTemp, $uploadDirectory)) { $productWM = watermark_image($uploadDirectory, $newFileName, 1); $productTH = resize_image($uploadDirectory, $newFileName, 1); } //move_uploaded_file($fileTemp, $uploadDirectory) /*if (isset($generate2ndImage)) { watermark_image($uploadDirectory2nd, $fileTemp2nd); move_uploaded_file($fileTemp2nd, $uploadDirectory2nd); } //isset($generate2ndImage)*/ $qI = mysql_query("INSERT INTO `fcpv3_products` (`id`,`category_id`,`product_name`,`product_description`,`product_thumbnail`,`product_fullsize`,`product_fullsize_second`,`product_price`,`product_weight`,`p_med`,`is_breakable`,`site`,`date_added`) VALUES ('','$productCT','$productNM','$productDS','$productTH','$newFileName','$newFileName2nd','$productPR','0.00','$productPM','N','US',NOW())"); if ($_POST['updateTwitter'] == "yes") { $last_product_id = mysql_insert_id(); $twitter_url = generate_seo_friendly_links($productNM, $last_product_id); $username = 'firstchoicephar'; $password = ''; $status = urlencode(stripslashes(urldecode('We just added ' . $productNM . ' http://www.firstchoicepharmacy.co.uk/product.php?id=' . mysql_insert_id()))); if ($status) { $tweetUrl = 'http://www.twitter.com/statuses/update.xml'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "$tweetUrl"); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, "status=$status"); curl_setopt($curl, CURLOPT_USERPWD, "$username:$password"); $result = curl_exec($curl); $resultArray = curl_getinfo($curl); if ($resultArray['http_code'] == 200) { print "<p class=\"fcp-message-success\">Tweet made successfully :).</p>"; } //$resultArray['http_code'] == 200 else { print '<p class="fcp-message-error">OOPS, an error has occured Posting to twitter, please contact the site administrator.</p>'; curl_close($curl); } } //$status if ($qI) { print "<p class=\"fcp-message-success\">You have successfully added a new product.</p>"; } //$qI else { print '<p class="fcp-message-error">OOPS, an error has occured please contact the site administrator.</p>'; } } //$_POST['updateTwitter'] == "yes" } elseif($productST == "UK") { if (move_uploaded_file($fileTemp, $uploadDirectory)) { $productWM = watermark_image($uploadDirectory, $newFileName); $productTH = resize_image($uploadDirectory, $newFileName); } //move_uploaded_file($fileTemp, $uploadDirectory) /*if (isset($generate2ndImage)) { watermark_image($uploadDirectory2nd, $fileTemp2nd); move_uploaded_file($fileTemp2nd, $uploadDirectory2nd); } //isset($generate2ndImage)*/ $qI = mysql_query("INSERT INTO `fcpv3_products` (`id`,`category_id`,`product_name`,`product_description`,`product_thumbnail`,`product_fullsize`,`product_fullsize_second`,`product_price`,`product_weight`,`p_med`,`is_breakable`,`site`,`date_added`) VALUES ('','$productCT','$productNM','$productDS','$productTH','$newFileName','$newFileName2nd','$productPR','0.00','$productPM','N','UK',NOW())"); if ($_POST['updateTwitter'] == "yes") { $last_product_id = mysql_insert_id(); $twitter_url = generate_seo_friendly_links($productNM, $last_product_id); $username = 'firstchoicephar'; $password = 'milr'; $status = urlencode(stripslashes(urldecode('We just added ' . $productNM . ' http://www.firstchoicepharmacy.co.uk/product.php?id=' . mysql_insert_id()))); if ($status) { $tweetUrl = 'http://www.twitter.com/statuses/update.xml'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "$tweetUrl"); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, "status=$status"); curl_setopt($curl, CURLOPT_USERPWD, "$username:$password"); $result = curl_exec($curl); $resultArray = curl_getinfo($curl); if ($resultArray['http_code'] == 200) { print "<p class=\"fcp-message-success\">Tweet made successfully :).</p>"; } //$resultArray['http_code'] == 200 else { print '<p class="fcp-message-error">OOPS, an error has occured Posting to twitter, please contact the site administrator.</p>'; curl_close($curl); } } //$status if ($qI) { print "<p class=\"fcp-message-success\">You have successfully added a new product.</p>"; } //$qI else { print '<p class="fcp-message-error">OOPS, an error has occured please contact the site administrator.</p>'; } } //$_POST['updateTwitter'] == "yes" } } //isset($_POST['submit-add-product']) ?> When i change the $us flag the US site works and the UK one doesn't, the full size image always gets uploaded fine it appears to be my logic in the resize function (i think ) a fresh pair of eyes would be great thanks guys Graham Hey All,
I'm creating a function in javascript and I'm having a bit of trouble trying to figure out the logic.
Here is the breakdown. I have a json database that will output some text into the main index.html file. This text is broken up into different entries each tagged with different categories. On the index.html the user clicks on the categories they want and then click on either one of two buttons.
The first button will show the text items that have any of the categories, so if they select categories 1 and 3, the function will show any of the text items with those categories. (This part works)
The second button i want to show text that only have all the selected categories. So if they selected category one and three, then only items with one AND three will show It could have other categories tagged, but it has to have the selected tags in the same item. I'm just trying to figure out how to isolate just those items.
Here is the code for the first button. I'm not a solid coder and most of this has been trial and error after error. I just need to figure out something similar for the second button.
function loadInfoOr() { $.getJSON('data.json', function(data) { var output = '<ul class="searchresults">'; $.each(data, function(key, val) { if ((val.env.search(env) != -1) || (val.pri.search(pri) != -1) || (val.per.search(per) != -1) || (val.ind.search(ind) != -1) || (val.com.search(com) != -1) || (val.res.search(res) != -1) || (val.myr.search(myr) != -1) || (val.saf.search(saf) != -1) || (val.ewa.search(ewa) != -1)) { output += '<li class="itemWrapper">'; output += '<h2>'+ val.Header; if ((val.env.search("ENV") != -1)) { output += '<span class="tag env">ENV</span>'; } if ((val.pri.search("PRI") != -1)) { output += '<span class="tag pri">PRI</span>'; } if ((val.per.search("PER") != -1)) { output += '<span class="tag per">PER</span>'; } if ((val.com.search("COM") != -1)) { output += '<span class="tag ind">IND</span>'; } if ((val.ind.search("IND") != -1)) { output += '<span class="tag com">COM</span>'; } if ((val.res.search("RES") != -1)) { output += '<span class="tag res">RES</span>'; } if ((val.saf.search("MYR") != -1)) { output += '<span class="tag myr">MYR</span>'; } if ((val.myr.search("SAF") != -1)) { output += '<span class="tag saf">SAF</span>'; } if ((val.ewa.search("EWA") != -1)) { output += '<span class="tag ewa">EWA</span>'; } output += '</h2>'; output += '<p>'+ val.statement +'</p>'; output += '</li>'; } }); output += '</ul>'; $('#textArea').html(output); }); }; Hey guys, I have a question that you can hopefully help me with, I'm writing a simple forum, and I'm wondering how I would go by handling a thread that has been 'stuck' so that it isn't moved when more threads are made. I could use some a push in the right direction thanks. |