PHP - Handling Big Numbers
Hi ..am new to PHP and am using it to solve some mathematical problems which require extensive computation.
Following is a code to solve a problem: Code: [Select] <?php $num =1; $n =0; $temp = 0; $count =0; $Final =0; While( $num < [color=orange]1000000)[/color] { $n = $num; while($n >1) { if(( $n % 2) == 0) { $n = $n/2; $temp++; } else { $n =3*$n +1; $temp++; } } If($temp > $count) { $count =$temp; $Final =$num; } $num++; $temp =0; } echo $Final; echo "<BR>"; echo $count; ?> I am running into "Maximum execution time of 30 seconds exceeded" error...its happening coz of the number 1 million...the code wrks fine for 100,1000,10000 and 100000...but breaks down @ 1000000.....is there any way to solve this situation...or PHP is not capable of handling huge numbers? please help...am stuck with this even though am so close to solving the prob. Thanks Abhijeet Similar TutorialsMy employer asked if I could change an existing contact form on their website to allow clients to enter their Social Security Number along with the normal contact information if the client decide to do so, instead of going through the motion of physically send in the form via snail mail, fax, or in person (like it is currently handled). But since this piece of information is of such delicate nature, I wonder how I should approach this from both a legal standpoint and from a programming standpoint. The form currently sends the information entered by the user to an inbox with mail(), so my initial thought was to somehow encrypt the information, limiting the risk of someone getting a hold of this information once the use user clicks "Send". But is full blown SSL really necessary for this? Are there easier options? And what should I think about before enabling this? Hi, I need to sort variables in groups of up to 15 and put it in an array. For example: $exstract['center_tabOpBody_0'] =5 $exstract['center_tabOpBody_1'] =6 $exstract['center_tabOpBody_2'] =8 $exstract['center_tabOpBody_3'] =1 Should yield: ARRAY( = center_tabOpBody_1,center_tabOpBody_2,center_tabOpBody_3 // <-----15 [1] = center_tabOpBody_0 //<----5 ) Is there some simple function do do the "efficiency" sort? Thanks, Vadim A form needs to get answers of math quiz, returning numbers, up to 2 digits after the point. In all form examples I noticed the usage of: Code: [Select] ...<input type="text" name="name" /... Cant it be a number? floating or integer? why "text" ? Also, can I limit the form to accept numerical input only or would I need to learn Ajax for that? Once I have the answer, I need to compare it to the correct answer. The method I have in mind is to multiply the answer and the correct one by 100 and compare the integer part. Is there a pre-made function that can do the same? Hi, I'm a beginner in PHP OOP and I'm with some doubts about the correct way of handling errors in PHP. Look at this function for example: public function deleteFileFromDisk($fileNameToBeDeleted) { $handle = unlink($fileNameToBeDeleted); if (!$handle) { $result = "(this->deleteFileFromDisk) - Error, " . $fileNameToBeDeleted . " not deleted."; } else { $result = "(this->deleteFileFromDisk) - Success, " . $fileNameToBeDeleted . " deleted."; } return $result; } Is this the correct way of doing it, or I can do better than this? Let me add some details of what I'm achieving... I'm running class methods, and I need to control errors in the process. If any call to the object throw an error I need to catch, stop all the process and send an e-mail with the error. Here are the object interactions: $testar_classe = new geoIpImportCSV('geolitecity', 'http://geolite.maxmind.com/download/geoip/database/GeoLiteCity_CSV/'); $testar_classe->downloadAndSaveFile('./', $testar_classe->obtainDownloadFileName()); $testar_classe->uncompressZipFile($testar_classe->obtainDownloadFileName(), '.'); $testar_classe->deleteLine(1, 'GeoLiteCity-Location.csv'); $testar_classe->deleteLine(1, 'GeoLiteCity-Blocks.csv'); $testar_classe->deleteDataFromTable('tabela1'); $testar_classe->deleteDataFromTable('tabela2'); $testar_classe->insertLinesToDb('GeoLiteCity-Location.csv', 'tabela1'); $testar_classe->insertLinesToDb('GeoLiteCity-Blocks.csv', 'tabela2'); $testar_classe->deleteFileFromDisk($testar_classe->obtainDownloadFileName()); $testar_classe->deleteFileFromDisk('GeoLiteCity-Blocks.csv'); $testar_classe->deleteFileFromDisk('GeoLiteCity-Location.csv'); Which is the best way of handle this? Create a new method to take care of the exceptions? There are any examples on how to do this? Best Regards. Hello, Am writing a script that involves user input. Take an example: a user fills in a wrong username or password at the page login.php, my login processor (processor.php) detects it, how is the error "WRONG USERNAME OR PASSWORD" supposed to be transferred back to login.php. So far I have been using a session variable to transfer the error but am sure there is a better way to do this without displaying the error on processor.php itself. Thanx in advance Hey Guys,
Been coding PHP for a while but I always wonder about the right way of doing things. I am building an online community which I want to display to members and non-members. With this each screen will have options that are available for members only. I have set up session variables once a user logged in but its getting really old having to nest if statements on ISSET then again to check the values in the variables if it is set. See example below.
Question 1. Is it ok to session_start(); for all site visitors?
Question 2. If Q.1 is ok then is it ok to set all the session variables upfront with blank values as placeholders. This would eliminate the need for ISSET.
if (ISSET($_SESSION['On'])) { if (in_array($GroupID, $_SESSION['Groups'])) { $IsMember = 1; } else {$IsMember = 0;} } else {$IsMember = 0;}Just wanted to get your thoughts on this. Thank you, Jeremy Hi, I have an HTML form created using Dreamweaver and now I need a script to handle the form processing. Basically what I need is for the form data received from the webpage to be organized in an email and then sent to me. I would also like to display a thank you message in the browser so the user knows it was received. I was planning to do this using CGI but a colleague suggested that CGI is old school and nowadays a developer would use PHP for this task. Is PHP the right solution for this project? The examples I have found so far always include the HTML for the form and the script needed to handle it in one file. In my case, I have an HTML form already in place and need it to work with a script to perform the email function. I know I need to set "Action=" on my webpage to point to the PHP script but what would the code look like if no HTML is needed? I hope this makes sense... Thanks for your help! Rob I am inserting last names into the database using mysql_real_escape_string(), and outputting the data into a textbox using addslashes(). When I try to display O'Brian "O\" is displayed in the text box. The name is saved corretly as O'Brian in the database. I am printing the string like this: Code: [Select] echo "<input type='text' value='" . addslashes($customer['lName']) . "' blah blah..."; anybody have any ideas? Hi I'm completely new to error handling in PHP and wanted to ask whether I'm doing it right and, if not, what the right way would look like class DBConnection { public function execute($sql) { $query = @pg_query($this->dbconn, $this->prepare($sql)); try { if (!$query) { throw new DBException(); } } catch (DBException $e) { echo "Query execution failed"; exit; } } } Whats the best way to handle database errors. I been using ob_start() stuff to run the code and if a database connection error occurs an variable $error turns to 1 and it displays the error code instead of the normal page that should be displayed when no errors occur. It works but I want to know if there is any better way to manage a db connection error while running a script. Also, how do you manage a problem when like 3 queries are ran to setup a new user account and the last one fails because the db connection drops or something, how would you go about handling a 2/3 query successful? I'm really stuck on how to manage errors if a db connection fails after the first connection is successful. I have a prepared statement that returns an Article from my database. It then binds the results-set to variables. Most of the fields in the query are "required", so I *assume* that I am guaranteed to always get values back for those fields... Is that presumptuous? Here is a snippet of my code... // Execute query. mysqli_stmt_execute($stmt); // Store results. mysqli_stmt_store_result($stmt); // Check # of Records Returned. if (mysqli_stmt_num_rows($stmt)==1){ // Article was Found. $articleExists = TRUE; // Bind result-set to variables. mysqli_stmt_bind_result($stmt, $articleID, $title, $description, $keywords, $heading, $subHeading, $publishedOn, $author, $body, $referenceListing, $endnoteListing); // Fetch record. mysqli_stmt_fetch($stmt); // Close prepared statement. mysqli_stmt_close($stmt); // ???? Is it sufficient to have code like this... Code: [Select] <title><?php echo $title; ?></title> ...or do I need more error-handling?? Hope that makes sense?! Thanks, Debbie I have set an SQL field as unique so that duplicates can't be entered, however rather then having the page error out and show the Error: Duplicate entry 'entry' for key 'field' I would like to be able to have a little div appear and say something like "this entry already exists" I already have it set to show that the item has been added but I have no idea were to start to make this work. Any ideas? Thanks, Jim Hello there, I'm having a problem displaying money correctly with php. I have a field called "balance" with the type float(10,2), in this field I have a number store as "34.55" which I can go in and look at within phpmyadmin but when I echo this value on the front-end of the site it is displayed as "34.549999237061" Can someone please help? Regards. I'm trying to develop a website file manager. I want to allow SSI, and would like to handle it specifically.. Code: [Select] $regexp = "<!--#include\s[^>]*virtual=(\"??)([^\" >]*?)\\1[^>]*\/-->"; if(preg_match_all("/$regexp/siU", $body, $matches, PREG_SET_ORDER)) { foreach($matches as $match) { $includeFile = $match[2]; } } This snippet shows how you would get the included file path in the SSI code of the website body [ the $body tag ], but I don't need to just find it- I want to replace the SSI code with a simpler code in the HTML that appears in the editor for easy management.. Then switch back from my easier code to the actual SSI code.. Example: Replace Code: [Select] <!--#include virtual="/newsManager/output.php"--> With Code: [Select] {INCLUDE=/newsManager/output.php} THEN when the user saves the page, Replace Code: [Select] {INCLUDE=/newsManager/output.php} With Code: [Select] <!--#include virtual="/newsManager/output.php"--> Is there an easy fix or should I just switch to a full blown template engine.. even though this is the only required feature? This doesn't work. Based off what I have seen online, it is suppose to. Basically, this is what I tried, and the quote is what was returned. I have no idea how to get this to work. It should have been pretty standard based off of the PHP documentation. The Xpath idea I got from someone else. Either way if I try to use find element by id or tag name it still returns an empty array, no matter what. Any advice on what I am doing wrong is appreciated. It doesn't matter what URL I try, none of them seem to work. Code: [Select] <?php $school_data = file_get_contents('http://www.infotechnologist.biz'); $doc = new DOMDocument(); $doc->validateOnParse = true; $doc->loadHTML($school_data); $xpath = new DOMXPath($doc); $tags = $xpath->query('div'); echo '<pre>'; print_r($tags); echo '</pre>'; ?> Quote DOMNodeList Object ( ) My script displays results until I hit an error. I continually get fatal timeout errors that I am unable to handle or ignore. Yes I googled and found the custom error handler AND the simpler try/catch. Still cant figure it out... It has been 1 hour of playing with this without success so I have to ask . Please help. thanks : ) Code: [Select] try { if(($result=shell_exec("$commandLine")) == false) { echo "------>error"; throw new Exception; } else { echo "---->good"; } } catch (Exception $e) { echo "@@@__>exception caught"; } Ok, so I am kind of just looking for some experience on this one. I am building a billing / referral system that works on a hierarchy. Now the hierarchy is simple and straight forward. However, I am trying to figure out the easiest / least error prone way of handling the payments. I have an IPN with paypal set up and working successfully. Here is how the system works: User signs up and refers several users. Each user pays $8 a month (paypal subscription). The system pays $1 7 levels deep. So The payment scheme would look like this: User 8 pays $1 to User 7, 6, 5, 4, 3, 2, and user 1. Then, the site keeps the remaining $1. I have the Paypal IPN saving the $8 payment transaction to the database. Now I need to divy it up, but I am split on when the best time to do this would be and how. There is a possibility that the user could pay a different amount less than or more than the $8 and they also pay a setup fee which should not be divided. It should only divide the shares when the current account is paid in full. Another thing to keep in mind, is that the $8 subscription, 7 levels deep, and the setup fee are variable numbers. (The admin may change it at any time.) I see multiple solutions, but not sure which would be best as all have possibility for errors in handling. Any advice would be helpful. Thanks, Tom I'm using xampp on windows vista I am a beginner in php and am working on creating a file hosting website got a form to upload the file from the client in uploadform.php Code: [Select] <html> <body> <form method="post" action="uploadfile.php" enctype="multipart/form-data"> <input type="file" name="usr" id="usr"/><br /> <input type="submit" value="Upload"/> </form> </body> </html> the file handling code is in uploadfile.php Code: [Select] <?php class upload { function fupload() { $dir = "C:\\xampp\htdocs\learning\fileshare database.txt"; echo "My name is: ".$_FILES['usr']['name']."<br/>"; echo "Location ".$_FILES['usr']['tmp_name']."<br/>"; echo "Size:".($_FILES['usr']['size'] / 1024)." kb <br/>"; echo "File type".$_FILES['usr']['type']."<br/>"; if(file_exists("htdocs/".$_FILES['usr']['name'])) { echo $_FILES['usr']['name']."already exists"; } else { copy($_FILES['usr']['name'],$dir); echo "File moved"; } } } $up = new upload(); $up->fupload(); ?> The problem is that it does not copy the file from the tmp directory to the specified one the error i get is: Warning: copy(fileshare databse.txt) [function.copy]: failed to open stream: No such file or directory in C:\xampp\htdocs\learning\uploadfile.php on line 20 I am facing the same problem if i try move_uploaded_file () function Could any one help with this issue, thanks Not sure why the PHP variables in the code below aren't interpreting the values that they should be receiving from the HTML form. HTML form Code: [Select] <form action="handle_form.php" method="post"> <fieldset><legend>Enter your information in the form below</legend> <p><b>Name:</b> <input type="text" name="name" size="20" maxlength="40" /></p> <p><b>Email Address:</b> <input type="text" name="email" size="40" maxlength="60" /></p> <p><b>Gender:</b> <input type="radio" name="gender" value="M" /> Male <input type="radio" name="gender" value="F" /> Female</p> <p><b>Age:</b> <select name="age"> <option value="0-29">Under 30</option> <option value="30-60">Between 30 and 60</option> <option value="60+">Over 60</option> </select> </p> <p><b>Comments:</b> <textarea name="comments" rows="3" cols="40"></textarea></p> </fieldset> <div align="center"><input type="submit" name="submit" value="Sumbit My Information" /></div> </form> PHP handle_form <?php #Script 2.2 handle_form.php $name = $_REQUEST['name']; $email = $_REQUEST['email']; $comments = $_REQUEST['comments']; echo "<p>Thank you, <b>$name</b>, for the following comments:<br /> <tt>$comments</tt></p> <p> We will reply to you at <i>$email</i>.</p>"; ?> I am uncertain of how to go about checking if my variables have values, and if I have to do this at every step in my code?! For instance... In my "Member" table, the fields "id" and "name" are required. So when I run this query, presumably there are always values there, right? Code: [Select] // Build query. $q = 'SELECT id, first_name FROM member WHERE email=? AND pass=?'; 1.) Is that a fair assumption? After the above code, I initialize these two variables... Code: [Select] // Initialize variables. $memberID = $memberFirstName = ''; Next I have... Code: [Select] // Bind result-set to variables. mysqli_stmt_bind_result($stmt, $memberID, $memberFirstName); 2.) Did I need to initialize those two variables if I am assigning them values a few lines down? 3.) Can I assume that "$memberID" and "$memberFirstName" will have values based on the comments above? Then a few more lines after this, I have... Code: [Select] // Set Session variables. $_SESSION['memberID'] = $memberID; $_SESSION['memberFirstName'] = $memberFirstName; $_SESSION['loggedIn'] = TRUE; 4.) Again, do I need to keep checking for values (e.g. using ISSET)?? I suppose *anything* is possible, but you could also make your code so full of error-checking code that it would come to a screeching halt?! Please enlighten me!! Debbie |