PHP - Issue With My Programming Logic?
This is probably less of a language-specific question and more one related to logic, but since it's written in PHP and it's been vexing me for a few hours now, I figured I'd take a shot asking about here!
Simple problem I'm trying to figure out for a class; I have a simple string of characters in the form "111-AAA" (three digits, hyphen, three letters) and I'm supposed to increment the string in a particular order. I increment the digits first, and after they've passed 999, I reset them to 000, increment the right-most column on the letters' side, and start again. I assumed this would be pretty simple, but the code I've written executes with some fairly strange results. With the file posted below, eight iterations into the outermost for() loop ought to echo "119-AAA", but I get "129-AAA" instead. And that's just the beginning - I started off with a thousand iterations so I could see just how drastically this little issue snowballs down the line. I see what's happening: before the value in the column being incremented is reset to 0 or A, the next column to be changed jumps the gun and gets incremented early. But no matter where I stick the increment expression, the same thing happens. I'm sure the problem is right here under my very nose, but I'm completely missing it...could anyone possibly show me what I'm not seeing? <html> <title>Test</title> <body> <?php $oldString = "111-AAA"; echo "Below this line is the string to be modified:<p>"; echo $oldString; echo "<p>And below this line is the modified string:<p>"; $newString = array($oldString[2], $oldString[1], $oldString[0], $oldString[6], $oldString[5], $oldString[4]); for($i=0; $i<1000; $i++) { for ($count = 0; $count < 6; $count++) { $newString[$count]++; if (($newString[$count] > 9) && ($count < 3)) { $newString[$count] = 0; break; } if (($newString[$count] == 'AA') && ($count > 2)) { $newString[$count] = 'A'; break; } if (($newString[$count] != 'AA') && ($newString[$count] != 9)) { break; } } echo $newString[2] . $newString[1] . $newString[0] . '-' . $newString[5] . $newString[4] . $newString[3] . "<br>"; } ?> </body> </html> Similar TutorialsHey all, trying to figure out a logic flaw in this validation script. Basically if I use !preg_match or the preg_match examples (noted below), I do not get the correct results.
My interpretation of preg_match and my current understanding of the logic is noted below (please correct me if I'm wrong).
1. If I use alternate attempt !preg_match, the regex would be compared against the "string" in the $email variable. If the regex expression matches, error will be thrown and script would stop.
2. If I use alternate attempt !preg_match, the condition would be not true and move to else where the string contained within $email variable would be run through the vld function.
3. If I maintain the current script using preg_match, if the string matches the match, the condition would be true and therefore string of $email variable runs through VLD function else cleanup and throw error...
Are my statements above correct in this context? I think I'm pretty close to cracking it but seem to be missing something simple.
The current script is referenced below, forgive me if I've lost the plot. Long hours attempting to understand this language, from what I've seen so far its great.
Thanks in advance,
A
//Alternate attempt
if (!preg_match("/^[^@]+@[^@.]+\.[^@]*\w\w/", $email)) { $error = "Please enter a valid email address"; } else { $email = vld($_POST['email']); } Current code that doens't work: if (empty($_POST['email'])) { $error = "Email is required"; } else { if (strlen($_POST['email']) < 5) { $error = "Email is too short!"; } else { if (strlen($_POST['email']) > 30) { $error = "Email is too long!"; } else { if (preg_match("/[\(\)\<\>\,\;\:\\\"\[\]]/", $email)) { $error = "The email address contains illegal characters"; } else { if (preg_match("/^[^@]+@[^@.]+\.[^@]*\w\w/", $email)) { $email = vld($_POST['email']); } else { $error = "Please enter a valid email address"; } } } } } } hello, im trying to read the database and store values into an array list. when i run the script it says undefined variable prodcode, name, price in the function prod details. any help pliz. appreciate the help. thnaks! require("dbfunctions.inc.php"); $count; class Product { // The following are the attributes of the Product class, that is, var $prodcode = array(); var $name = array(); var $price = array(); /* CONSTRUCTOR Every class has at least one constructor method. We create an instance of a class using the class's constructor */ function AllProducts() { $qry = "Select ProdCode, Name, Price, Image from products"; //execute query $products = execute_query($qry); if (!$products) {die('query failed.'); } $i = 0; global $count; $count= mysql_num_rows($products); while ($line = mysql_fetch_array($products, MYSQL_ASSOC)) { $prodcode =array ($line['ProdCode']); //$name[$i] = $line['Name']; //$desc[$i] = $line['Desc']; //$price[$i] = $line['Price']; //$category[$i] = $line['Category']; $i++; } } // Method to print the Shopping Cart details to the screen function ProdDetails() { global $count; echo $count; echo $count; for ($i = 0; $i <= $count; $i++) { //echo "<tr><td>"; echo "<br>Product Code: <a href=DisplayProduct.php?prodcode=" . $prodcode[$i]. ">" .$prodcode[$i]. "</a>"."<br>"; echo "Product Name: ".$name[$i]." <br>". "Price: FJD$ " .$price[$i]."<br>"; } } // Method to print the Shopping Cart details to the screen function getProdCode() { echo "Product Code: " . $this->prodcode . "<br>"; } } // END OF CLASS 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 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. 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 :/ 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 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? 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 Hii.... I simply want to know the answer of a simple question "Is it possible to do Window Programming in PHP?", like C++, .net, etc.....and if so then where I can find links for the tutorials..... Hi all, I am trying to create a socket that can read from and write to a client. This is my first attempt at it and the code in question is based more or less on a python script a friend sent me as well as some php tutorials google supplied. The problem is (and this seems to be a reoccurring one) when I run it from the command line Code: [Select] php -q server.php nothing visibly happens. Can anyone see what the problem might be? Code: [Select] <?php $host = "localhost"; $port = 50007; set_time_limit(0); // no timeout $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n"); // create $result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n"); // bind $result = socket_listen($socket, 3) or die("Could not set up socket listener\n"); // listen echo "Waiting for connections...\n"; $contact = socket_accept($socket) or die("Could not accept incoming connection\n"); // accept $input = socket_read($contact, 1024) or die("Could not read input\n"); // read $input = trim($input); // clean $output = "Greetings, you have connected to a socket.\n"; socket_write($contact, $output, strlen ($output)) or die("Could not write output\n"); // return socket_close($contact); // close socket socket_close($socket); // close socket ?> Alright.. I guess to start this off I am looking to sometime in the near future start building a web based or browser based application that I want to build a part of the interface to be a gps module. this will be for a self hosted application likely on tablets or laptops where it will use the data for tracking information amongst other things. Any way most of the application is being handled in PHP, mySQL, jQuery. So with that my question is, is there any way to build a gps application with that as the core languages used. If it is possible, whats the best gps unit I can use? remember im not nessisarily looking for a fancy gps unit to do this with.. just a transmitter/reciever is fine so long as I can build software of my own around it, also is it actually possible to do this with something like php/jquery? or is this something I would have to go the route of maybe java to handle the hardware transactions of which I can tie php/jquery into that.. I am adding a comments "wall" (similar to facebook or youtube) on my site, and here is the condition it's currently in: http://www.trancetrackonline.com/index.php I am not a very good programmer, but I just need to make a couple small changes to the script. I don't want to include "email" or "homepage" fields, since they are not relevant for me. Also, if possible (though the first thing is more important), I'd like to figure out how to make the advertisement at the bottom of the board ("...provided by gentlescript...") a little bit small, since right now it is very obtrusive. many thanks in advance to anyone who can figure this out!!!!!! The scripts are attached, but Here is the comments.tpl.html script: {call_module trigger="frontend_content_footer" data="$page_data"} <!-- Comment List Start --> <a name="c5t_comment"></a> <h2 class="c5t_headline">{$txt_comment_headline} ({$result_number})</h2> <div class="c5t_comment_list"> {foreach from=$comment_list item=item} <div class="c5t_comment_item_background"> <div class="c5t_comment_item"> <div class="c5t_comment_item_title">{$item.comment_title}</div> <div class="c5t_comment_item_text">{$item.frontend_text}</div> <div class="c5t_comment_item_details">#{$item.comment_number} - {if $item.comment_author_homepage != '' and $item.comment_author_homepage != 'http://'}<a href="{$item.comment_author_homepage}">{$item.comment_author_name}</a>{else}{$item.comment_author_name}{/if} - {$item.comment_date} - {$item.comment_time}</div> </div> </div> {/foreach} </div> <!-- Comment List End --> <!-- Pagination Form Start --> {if $comment_list and $display_pagination} <div class="c5t_frontend_pagination"> {if $browse_previous == 2} <form {$startpage.attributes}>{$startpage.hidden}{$startpage.start.html}</form> <form {$previouspage.attributes}>{$previouspage.hidden}{$previouspage.previous.html}</form> {else} <span>{$txt_start}</span> <span>{$txt_previous_page}</span> {/if} {if $browse_next == 2} <form {$nextpage.attributes}>{$nextpage.hidden}{$nextpage.next.html}</form> <form {$endpage.attributes}>{$endpage.hidden}{$endpage.end.html}</form> {else} <span>{$txt_next_page}</span> <span>{$txt_end}</span> {/if} </div> {/if} <!-- Pagination Form End --> <!-- Comment Form Start --> <a name="c5t_form"></a> <div class="c5t_comment_form_background"> <form {$form.attributes}> <table class="c5t_comment_form_table"> <tr> <td colspan="2" class="c5t_error_message"> {foreach from=$message item=item} <div class="c5t_error_message_item">{$item}</div> {/foreach} </td> </tr> {if $show_form == "yes"} <tr> <td class="c5t_comment_form_label"> {if $form.name.error} <span class="c5t_error_message">{$form.name.error}</span> {else} {$form.name.label} {/if} </td> </tr> <tr> <td class="c5t_comment_form_field"> {$form.name.html} </td> </tr> <tr> <td class="c5t_comment_form_label"> {if $form.email.error} <span class="c5t_error_message">{$form.email.error}</span> {else} {$form.email.label} {/if} </td> </tr> <tr> <td class="c5t_comment_form_field"> {$form.email.html} </td> </tr> <tr> <td class="c5t_comment_form_label">{$form.homepage.label}</td> </tr> <tr> <td class="c5t_comment_form_field"> {$form.homepage.html} </td> </tr> <tr> <td class="c5t_comment_form_label">{$form.title.label}</td> </tr> <tr> <td class="c5t_comment_form_field"> {$form.title.html} </td> </tr> <tr> <td class="c5t_comment_form_label"> {if $form.$comment_field_name.error} <span class="c5t_error_message">{$form.$comment_field_name.error}</span> {else} {$form.$comment_field_name.label} {/if} </td> </tr> <tr> <td> {call_module trigger="frontend_textarea" field=$comment_field_name} </td> </tr> <tr> <td class="c5t_comment_form_field"> {$form.$comment_field_name.html} </td> </tr> <tr> <td class="c5t_comment_form_field"> {call_module trigger="frontend_comment_form"} </td> </tr> <tr> <td class="c5t_comment_form_label"></td> </tr> <tr> <td class="c5t_comment_form_submit">{$form.save.html}{$form.hidden}</td> </tr> {/if} </table> </form> </div> <!-- Comment Form End --> and here is the layout.tpl.html script: <div id="c5t_body"> <div id="c5t_bodycontent"> <!-- Language selection (link list or dropdown menu) --> {include file='default/language.tpl.html'} {foreach from=$system_messages item=item} <div class="c5t_system"> <div class="c5t_index">{$item.title}</div> <div class="c5t_code"><br />{$item.message}</div> </div> {/foreach} {foreach from=$error_messages item=item} <div class="c5t_system"> <div class="c5t_index">{$item.title}</div> <div class="c5t_code"><br />{$item.message}</div> </div> {/foreach} {call_module trigger="frontend_page_header"} {include file=$detail_template} {call_module trigger="frontend_page_footer"} {foreach from=$debug_messages item=item} <div class="c5t_system"> <div class="c5t_index">{$item.title}</div> <div class="c5t_code"><br />{$item.message}</div> </div> {/foreach} </div> </div> Its like an elusive goal of mine. To be able to write big pieces of code that are reusable in multiple projects.
For example: Lets say we are coding a simple 'Membership system'- login / signup etc.
How would for instance something like routing would be handled in this so that it remains modular. Reusable in multiple projects that may be using a different router for their projects.
Any guidance please ? Is there a book that shows how its done ?
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. 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:) 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. 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 I have a referal system. I want to have a reward for referring someone. I allocate a certain amount for the referal system (lets say $50). At level 1, nothing is given until you start referring people and the person(s) starts using the program. On level 2 you earn 9%($4.5 of $50) on level 3 you earn 27% On level 4 you earn 64% How do i go about this bearing in mind that a level 2 or 3, eventually becomes level 1 if he starts inviting people and those he invited starts using the program. Thanks 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 } } 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(); ?> |