PHP - Sanitised Code Stopping At &
The code I am using designed to display the terms I am using in my search.
For example: .php?description=red&purple&widgets displays red and purple widgets. However, I am also echoing the terms so people know what they are searching for: "Your are searching for red and purple widgets" However, by using the & sign it now displays "Your are searching for red" If I using .php?description=red%purple%widgets then nothing is displayed. Code: [Select] function sanitizeString($description) { $description = mysql_real_escape_string($description); $description = stripslashes($description); $description = htmlentities($description); return $var; Similar TutorialsI have below script. it does the while loop 100%. it updates the mysql database one at a time as it should. the problem I have now is that the while loop does not end and go to the next statement as it should. it keeps pollong the database. so when in back end you change to 0 it automatically updates again. Please see if you can help me to see where I can stop this while loop when there are no more loops // Here I select the amount of rows $sql_query = "SELECT ae FROM `debitorderrejectionimport` WHERE ae = '0'"; $rowCount = mysqli_query($conn,$sql_query); $rowCountUpdate = mysqli_num_rows($rowCount); echo $rowCountUpdate; while($rowCountUpdate > 0) { $sql = "UPDATE `ttee`.`au1` INNER JOIN `ttee`.`au` ON (`au1`.`id` = `au`.`id`) INNER JOIN `ttee`.`ae1` ON (`ae1`.`idd` = `au1`.`idd`) INNER JOIN `ttee`.`debitorderrejectionimport` ON (`debitorderrejectionimport`.`nr` = `ae1`.`id`) SET `au`.`amount` = `ae1`.`amount` + `au1`.`amount`, `debitorderrejectionimport`.`ae` = au.id ;"; $result = mysqli_query($conn, $sql); $updated = mysqli_affected_rows($conn); $rowCountUpdate - ($updated);} // if it finished updating and there is no more rows it must continue with below query mysqli_query($conn, " INSERT INTO `sataxicrm754`.`debitorderrejectionimport_back` ( `Outbound`, `Allocation`, `AccountName`, `QueryComplaintType`, `QueryStatus`, `Querytypeoption`, `Description`, `DealID`, `Deals`, `Assignedusername`, `Teams`, `CampaignName`, `CampaignID`, `inserted`, `idnumber`, `nr`, `datew`, `premium`, `policynumber`, `ContactNumber`, `CollectionType`, `OpportunityAmount`, `Broker`, `impref`, `id` ) SELECT `Outbound`, `Allocation`, `AccountName`, `QueryComplaintType`, `QueryStatus`, `Querytypeoption`, `Description`, `DealID`, `Deals`, `Assignedusername`, `Teams`, `CampaignName`, `CampaignID`, `inserted`, `idnumber`, `nr`, `datew`, `premium`, `policynumber`, `ContactNumber`, `CollectionType`, `OpportunityAmount`, `Broker`, `impref`, `id` FROM `sataxicrm754`.`debitorderrejectionimport` WHERE QueryComplaintType <> 'QueryComplaintType' ");
I have the following code that cycles though and prints out the day of the week and stops printing after the seventh day is reached, but it keeps looping. How do I stop it from looping after 7? I thought I had it right, but it's not. Can anyone help? Code: [Select] <?php $weekdays = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"); echo current($weekdays) . "<br />"; while (count($weekdays) < 8) { echo next($weekdays) . "<br />"; } ?> I have a script which registers people to a database, however it doing something very strange. Whenever I place it into even a single CSS div it adds the registration to the dabase but stops loading the next page (index.php) I find this totally bizarre as I haven't seen anything like this behave before. With CSS affecting how PHP works. Especially when the CSS is not inside the <php> of <form> tags. Code: [Select] <?php include("connect.php"); if($_POST['submit']) { $username = mysql_real_escape_string(trim($_POST['username'])); $password = trim($_POST['password']); $password2 = trim($_POST['password2']); $email = mysql_real_escape_string(trim($_POST['email'])); $error = false; if(!isset($username) || empty($username)) { $error = "You need to enter a username."; } $query = mysql_query("SELECT id FROM users WHERE username = '".$username."' LIMIT 1"); if(mysql_num_rows($query) > 0 && !$error) { $error = "Sorry, that username is already taken!"; } if((!isset($password) || empty($password)) && !$error) { $error = "You need to enter a password."; } if((!isset($password2) || empty($password2)) && !$error) { $error = "You need to enter your password twice."; } if($password != $password2 && !$error) { $error = "The passwords you entered did not match."; } if((!isset($email) || empty($email)) && !$error) { $error = "You need to enter an email."; } if(preg_match("/[a-zA-Z0-9-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/", $email) == 0 && !$error) { $error = "The email you entered is not valid."; } $query = mysql_query("SELECT id FROM users WHERE email = '".$email."' LIMIT 1"); if(mysql_num_rows($query) > 0 && !$error) { $error = "Sorry, that email is already in use!"; } if(!$error) { $query = mysql_query("INSERT INTO users (username, password, email) VALUES ('".$username."', '".mysql_real_escape_string(md5($password))."', '".$email."')"); if($query) { $message = "Hello ".$_POST['username'].",\r\n\r\nThanks for registering! We hope you enjoy your stay.\r\n\r\nThanks,\r\nJohn Doe"; $headers = "From: ".$website['name']." <".$website['email'].">\r\n"; mail($_POST['email'], "Welcome", $message, $headers); setcookie("user", mysql_insert_id(), $time); setcookie("pass", mysql_real_escape_string(md5($password)), $time); header("Location: index.php"); } else { $error = "There was a problem with the registration. Please try again."; } } } ?><html> <head> <title>Register</title> </head> <body> <form action="" method="post"> <?php if($error) echo "<span style=\"color:#ff0000;\">".$error."</span><br /><br />"; ?> <label for="username">Username: </label> <input type="text" name="username" value="<?php if($_POST['username']) echo $_POST['username']; ?>" /><br /> <label for="password">Password: </label> <input type="password" name="password" value="<?php if($_POST['password']) echo $_POST['password']; ?>" /><br /> <label for="password2">Retype Password: </label> <input type="password" name="password2" value="<?php if($_POST['password2']) echo $_POST['password2']; ?>" /><br /> <label for="email">Email: </label> <input type="text" name="email" value="<?php if($_POST['email']) echo $_POST['email']; ?>" /><br /><br /> <input type="submit" name="submit" value="Register" /> </form> </body> I'm writing PHP for my son's cub scout pack. It populates the MySQL db users table from data contained in a csv file. So far, it puts the scout's info in just fine...until I try to run another query as a nested query to retrieve the auto-generated userID for the scout that was just placed in the DB. The result of this if I don't include the second query--the one trying to get the new userID for that scout, it iterates through the whole file as expected and puts all the scouts in the users table. The second I uncomment the 2nd query and try to get it to run, it only puts the 1st scout in the DB, properly retrieves the newly generated userID for him, and then stops. I need to have this userID for the scout to properly associate that scout with the parents later on and in other sections of this project. the db_connect() function just creates the PDO object and contains the username, etc for the connection. That part is working fine so I'm not posting that function here. I've tried renaming the connection, query, etc to add "ID" to the end to ensure I wasn't trampling on var names, but that hasn't made a difference Code: [Select] //include necessary files: include_once("../../sys/php/includes/data_fns.php"); //start session session_start(); $conn = db_connect(); $bufferConn = $conn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true); //////////////////////////////////////// // Read through the .csv file and populate the users table /* Uses the model from the php documentation on fgetcsv: * $row = 1; if (($handle = fopen("test.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $num = count($data); echo "<p> $num fields in line $row: <br /></p>\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "<br />\n"; } } fclose($handle); } */ //////////////////////////////////////// $row = 0; //set the row counter $table1 = "<table id='csvTable'>"; //start the table HTML markup if(($handle= fopen("../../sys/source/pack238.csv", "r"))!== FALSE) //open the csv file { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) //fgetcsv reads through the csv file line by line { //ignore the first row which has the header data--we don't want that in the database if($row==0){$row++; continue;} $num = count($data); //get the scout's info, check to see if he's already in the db, then put it in if not--the scout should NOT already be in db when we run this for the first time, but later versions will only add new scouts. For now, just alert us if they're already in and halt //TODO Figure out why this still runs if the table name doesn't exist!! $query = "SELECT * FROM users WHERE fName=:firstName && lName=:lastName"; $stmt = $conn->prepare($query); $stmt->execute(array(':firstName'=>$data[1], ':lastName'=>$data[0])); $dbCount=0; while ($stmt->fetch()){$dbCount++;} if($dbCount >0) //we found this scout--he shouldn't be in the DB. Halt the process and check what's going on { echo "<br/>The scout, $data[1] $data[0] was found in the database already. We cannot continue. <b/>Please check this duplicate data and try running this setup again"; die(); } else //he's not in the DB....put him in there { //get the Den unit as a number, dropping "Den" $den = substr($data[10],4); //get birthday as something to be used as PHP date object if($data[7]!="") { $bdayO = date_create($data[7]); $now = date_create("now"); $interval = date_diff($bdayO, $now); $age = $interval->format('%y years'); $bday = $bdayO->format('Y-m-d'); } else{ $bdayO = NULL; $bday = NULL; $age = NULL; } echo "<br/> Test message: The scout $data[1] $data[0], Den:$den would be put into the database! His bday is:$bday. AGE IS: $age"; $query = "insert into users (gen,fName,lName, nName,memberOf,bday) VALUES ('M',:firstName,:lastName,:nickName,:den,:bday)"; $stmt= $conn->prepare($query); $stmt->execute(array(':firstName'=>$data[1], ':lastName'=>$data[0], ':nickName'=>$data[3], ':den'=>$den, ':bday'=>$bday)); //get the new userID for this scout now that he's in the db $connID = db_connect(); $queryID = "SELECT userID from users WHERE fName=:firstName && lName=:lastName"; $stmtID = $connID->prepare($queryID); $stmtID->execute(array(':firstName'=>$data[1], ':lastName'=>$data[0])); while ($row = $stmtID->fetch()) { $scoutUserID = $row[0]; echo "<br/>This scout's userID is: $scoutUserID"; } }//end else //get the father's info, check to see if he's already in the db, then put it in if not //if he is in the db, get this scout's userID number and add it to the father's children array $query = "SELECT * FROM users WHERE fName=:firstName && lName=:lastName"; $stmt = $conn->prepare($query); $stmt->execute(array(':firstName'=>$data[18], ':lastName'=>$data[19])); $dbCount=0; while ($stmt->fetch()){$dbCount++;} if($dbCount >0) //This father is already in the DB...we need to add this scout to his children array { echo "<br/>For testing purposes, this father is already in the DB...let's add this scout, ".$data[1]." to his children array"; //get the userID of the current scout } else //he's not in the DB....put him in there {} //get the mother's info, check to see if he's already in the db, then put it in if not //if she is in the db, get this scout's userID number and add it ot the mother's children array }// end while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) }//end if(($handle= fopen("../../sys/source/pack238.csv", "r"))!== FALSE) how do i stop multiple duplications in database on my PHP script? ok i have attached a screenshot of what the database looks like after a few runs of my script. the script is designed to pull api information, input into 1 database and update another user table. i have made it run as a cron job every 60 minutes. here is my code: <?php /* You need multiple instances of this script. Each instance runs once every hour so 6 instances means one runs every 10 mins. Remember to change the API URL to reflect the different accounts or characters.*/ include "connect.php"; $columns = "`date` , `refID`, `refType`, `ownerName1`, `ownerName2`, `argName1`, `amount`, `balance`, `reason`"; //Live URL is //Assumeing that they are only donating at this time and no one is being paid to reduce the balance. Balance reduction can be done in the prize claim script so its not API delayed. if ( ($data[2] == "Player Donation") && ($data[4] == "Ship Lotto")){ $reUsed = mysql_query("SELECT * FROM bank WHERE refID='$data[1]';"); if(!empty($reUsed)){ $import="INSERT into bank($columns) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]')"; mysql_query($import) or die(mysql_error()); } /*check to see if the player has already been credited. It checks the last recorded reference # and checks to see if the new ref # is greater, else skips the processing. You need to check since the API gives you the last 1000 journal entries or 1 week, what ever is shorter. Not just what is new since last check. Check is performed by seeing if the record in the database for the user is less then or equal to the new once. This works only because CCP's reference #s are auto increasing so they only go up if they are newer, never down.*/ $name = $data[3]; //echo "Updating account of ".$name."<br />"; $queryLastRef = mysql_query("SELECT lastRef FROM users WHERE username='$name';") or die(mysql_error()); //echo $queryLastRef; $arraylastRef = mysql_fetch_assoc($queryLastRef); $lastRef = $arraylastRef["lastRef"]; //echo "The last reference # was: ".$lastRef."<br />"; $currentRef = $data[1]; //echo "The current reference # is: ".$currentRef."<br />"; if($lastRef<$currentRef){ $amount = $data[6]; //echo "Player deposited ISK in the amount of: ".$amount."<br />"; $queryBal = mysql_query("SELECT user_iskbalance FROM users WHERE username='$name';") or die(mysql_error()); //echo "Executing the SQL command to query balance ID#: ".$queryBal."<br />"; $getBal = mysql_fetch_assoc($queryBal); //echo "Executing the SQL command to get balance amount: ".$getBal["user_iskbalance"]."<br />"; $deposit = $amount+$getBal["user_iskbalance"]; //echo "Depositing ISK in the ammount of: ".$deposit."<br />"; $importBal= "UPDATE users SET user_iskbalance=$deposit WHERE username='$name';"; //echo "Executing the SQL command to desposit: ".$importBal."<br />"; mysql_query($importBal) or die(mysql_error()); $importRefID= "UPDATE users SET lastRef='$currentRef' WHERE username='$name';"; //echo "Executing the SQL command to set the new reference: ".$currentRef."<br />"; mysql_query($importRefID) or die(mysql_error()); //echo "Success!"."<br />"; //For the sake of stats tracking update the total isk on deposit. The payout script will subtract. $queryiskDeposit = mysql_query("SELECT iskDeposit FROM stats;") or die(mysql_error()); //echo "Executing the SQL command to query the ISK deposited : ".$queryiskDeposit."<br />"; $arrayiskDeposit = mysql_fetch_assoc($queryiskDeposit); $getiskDeposit = $arrayiskDeposit["iskDeposit"]; //echo "Got total isk on deposit of: ".$getiskDeposit."<br />"; $iskDeposit = $getiskDeposit+$deposit; //echo "Inserting: ".$iskDeposit." ISK"."<br />"; $importiskDeposit= "UPDATE stats SET iskDeposit='$iskDeposit';"; //echo "Executing the SQL command to desposit: ".$importBal."<br />"; mysql_query($importiskDeposit) or die(mysql_error()); //echo "<br />"; //echo "<br />"; //echo "NEXT!<br />"; //echo "<br />"; } else{ //echo "There is no update for ".$name." because ".$lastRef." is not less then or equal to ".$currentRef."<br />"; //echo "<br />"; //echo "<br />"; //echo "NEXT!<br />"; //echo "<br />"; } //echo "DEBUG for ".$name." lastRef ".$lastRef." and currentRef ".$currentRef."<br />"; //update the time that last update ran $today = date("Ymd G:i"); mysql_query("UPDATE stats SET iskLastUpdate='$today';") or die(mysql_error()); //echo "Updating Date to: ".$today; //echo "<br />"; //echo "<br />"; //echo "NEXT!<br />"; //echo "<br />"; } } ?> can anyone help me stop it duplicating the entries in the database please? I wrote a small application to force downloads of various large video files using readfile. This worked fine. However, the users have changed hosts and now it doesn't work. Small files are fine, but large files will cut off before finishing. Test file is 114MB, but it is always cut off at exactly 67.2MB or 51.4MB depending on a couple criteria. I've stripped the application down to the key part that's not working and run it on a test page the just immediately goes the file - no logins or any of that shenanigans and htaccess blocking either: $file = some/file/on/the/server.wmv; //114MB hea der('Content-Description: File Transfer'); hea der("Content-Type: application/octet-stream"); hea der("Content-Disposition: attachment; filename=" .basename($file)); hea der("Content-Transfer-Encoding: binary"); hea der('Expires: 0'); hea der('Cache-Control: must-revalidate, post-check=0, pre-check=0'); hea der('Pragma: public'); hea der('Accept-Ranges: bytes'); hea der("Content-Length: ".filesize($file)); ob_clean(); flush(); @readfile($file); (gaps in the header words are to prevent forum breakage) I've tried the following variations: transfer encoding - chunked (this results in getting a 51.4 MB download rather than 67.2) content-type application/force-download tried the default force-download code from the php.net manual tried the chunking function variations on php.net readfile page tried without accept ranges originally (only spotted that on this site) set_time_limt to one hour set max memory to 300MB (phpinfo has shown these changes did get accepted) used htacess to disable gzip and deflate (this results in getting a 51.4 MB download rather than 67.2) (SetEnv no-gzip dont-vary or RewriteEngine On RewriteRule . - [E=no-gzip:1] or RemoveOutputFilter DEFLATE html txt xml css js php wmv) None of these have solved the issue. The code worked fine on the old site, works fine on my site, and works fine on my test server. Direct downloads from the broken site also work fine, just not readfile downloads. The filesize is reading correctly if I echo just that, and it reads properly on the progress bar when downloading through readfile. The hosting company are blaming my coding. The htaccess is the bit I'm least sure of and I find it hard to get solid info on this part on the web. Is there anything wrong with my code that could be causing this? Am I missing something? What could be causing the problem? Many Thanks Hi all, I am managing a social network and am creating a script to allow the admin to private message all users on the site. Even setting the max execution time to unlimited within the file does not allow us to insert all 40,000 rows into the 'message' table, it stops after several thousand rows. Our hosts tell us setting this globally is a bad idea/unstable. Does anyone have some advice on the best to do this? No email notifications need to be sent so it is purely allowing the script to run it's full course without stopping. I did consider a cron job but without emails doing in 'batches' seems a bit unecessary so I'm clearly missing something. ANy and all advice would be most welcome! Richard I'm attempting to praise(if that's how you say it) txt data into xml with php and have come across a problem I've been unable to solve over the past two days so I'm coming here to ask the php gods for their assistance. The file I'm prasing contains line after line of real estate data. I understand what I'm doing I think. I've gotten the data in a format that is more usable, taking out the tabs and replacing them with spaces and such. I am creating a series of if than statements which will select the address out of each line even though each line can be different. At the end of the address on each line there is a "S" character which stands for some property I'm not concerned with. I'm simply using the single 'S' to find the end of the address. The lines look like so: \/ 403089 RESIDENTIAL Residential 385000 7610 N Lakeshore Dr. Harbor Springs S 3 2 0 None 3 Litzenburger, Boo Schaffer Real Estate 399562 RESIDENTIAL Condominium 155000 4749 Pleasantview Road Harbor Springs S 2 2 0 One Hartwick, Bob Coldwell Banker Schmidt With a bunch of extra text following that I've trimmed off for our purposes here. See the 'S' after the town? I've created the following code to look for the 's' in relation to the word order. Code: [Select] <?php // Listings file $listings= file('listingsTest.txt'); $i = 0; $j = 0; $_ENV['a'] = 0; foreach($listings as $value) { //Replace all spaces of every kinds with single spaces $listings[$i] = preg_replace("'\s+'", ' ', $listings[$i]); //Put all characters into an array corisopndings to each line in $listings $_ENV['chars'.$i] = preg_split('//', $listings[$i]); //Place all words and uninterupted numbers and place in array $words $_ENV['words'.$i] = preg_split('/ /', $listings[$i]); $i++; } //echo $_ENV['chars'.'1']['1']; foreach($_ENV['words'.$_ENV['a']] as $char){ $countedf = preg_split('//', $_ENV['words'.$_ENV['a']][$j]); $counted = count($countedf) - 2; $wordBeforef = preg_split('//', $_ENV['words'.$_ENV['a']][$j-1]); $wordBefore = count($wordBeforef) - 2; $wordAfterf = preg_split('//', $_ENV['words'.$_ENV['a']][$j+1]); $wordAfter = count($wordAfterf) - 2; if( ($counted == 1) && ($wordAfter == 1) && (is_numeric($_ENV['words'.$_ENV['a']][$j+1])) //&& ($wordBefore == 1) //&& (!is_numeric($_ENV['words'.$_ENV['a']][$j])) //&& (is_numeric($_ENV['words'.$_ENV['a']][$j+2])) //&& ($_ENV['words'.$_ENV['a']][$j+3] == ' ' ) ){ echo '*'; echo $_ENV['words'.$_ENV['a']][$j]; echo '*'; $_ENV['a']++; $j =0; //$j=1 } //echo $_ENV['chars'.$_ENV['a']][$j]; $j++; } ?> As you can see from the if then statements, I've gotten to the point where It's replying to the 'S' at the end of the address thus telling me where the address ends. I am however having a problem I believe is a server issue. The code works fine when applied to 12 lines like the ones above, when I apply it to more of those lines it does not return the 'S' for them even if I used the exact same line more than 12 times. The main file which I'd like to automate the parsing of has thousands of these such lines in it. If I try to apply this code to the file with these thousands of lines, the browser returns a "The website encountered an error while retrieving http://localhost. It may be down for maintenance or configured incorrectly". I take this to mean the server is doing too much work for it to be completed. I think when it reaches it's twelfth, the temporary memory of my program/server or some thing else, is exhausted. I'm applying these if then statements to every single word in the file. Is this a processing issue on the server? I was applying this code to every character in the file and thought I could fix the problem by applying instead to every word given there are less words than characters. I have the processing time on the server set to 10000 and it's not taking along time to return the error message. I would be very grateful to any help any of you could provide. Thank you for your time. Hi, I have some code which displays my blog post in a foreach loop, and I want to add some social sharing code(FB like button, share on Twitter etc.), but the problem is the way I have my code now, creates 3 instances of the sharing buttons, but if you like one post, all three are liked and any thing you do affects all of the blog post. How can I fix this? <?php include ("includes/includes.php"); $blogPosts = GetBlogPosts(); foreach ($blogPosts as $post) { echo "<div class='post'>"; echo "<h2>" . $post->title . "</h2>"; echo "<p class='postnote'>" . $post->post . "</p"; echo "<span class='footer'>Posted By: " . $post->author . "</span>"; echo "<span class='footer'>Posted On: " . $post->datePosted . "</span>"; echo "<span class='footer'>Tags: " . $post->tags . "</span>"; echo ' <div class="addthis_toolbox addthis_default_style "> <a class="addthis_button_facebook_like" fb:like:layout="button_count"></a> <a class="addthis_button_tweet"></a> <a class="addthis_counter addthis_pill_style"></a> </div> <script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script> <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=webguync"></script>'; echo "</div>"; } ?> I have the following code in html: <html> <head> <script type="text/javascript"> <!-- function delayer(){ window.location = "http://VARIABLEVALUE.mysite.com" } //--> </script> <title>Redirecting ...</title> </head> <body onLoad="setTimeout('delayer()', 1000)"> <script type="text/javascript"> var sc_project=71304545; var sc_invisible=1; var sc_security="9c433fretre"; </script> <script type="text/javascript" src="http://www.statcounter.com/counter/counter.js"></script><noscript> <div class="statcounter"><a title="vBulletin statistics" href="http://statcounter.com/vbulletin/" target="_blank"><img class="statcounter" src="http://c.statcounter.com/71304545/0/9c433fretre/1/" alt="vBulletin statistics" ></a></div></noscript> </body> </html> Is a basic html webpage with a timer redirect script and a stascounter code. I know a bit about html and javascript, but almost nothing about php. My question is: How a can convert this html code into a php file, in order to send a variable value using GET Method and display this variable value inside the javascript code where says VARIABLEVALUE. Thanks in adavance for your help. Hi, I need to insert some code into my current form code which will check to see if a username exist and if so will display an echo message. If it does not exist will post the form (assuming everything else is filled in correctly). I have tried some code in a few places but it doesn't work correctly as I get the username message exist no matter what. I think I am inserting the code into the wrong area, so need assistance as to how to incorporate the username check code. $sql="select * from Profile where username = '$username'; $result = mysql_query( $sql, $conn ) or die( "ERR: SQL 1" ); if(mysql_num_rows($result)!=0) { process form } else { echo "That username already exist!"; } the current code of the form <?PHP //session_start(); require_once "formvalidator.php"; $show_form=true; if (!isset($_POST['Submit'])) { $human_number1 = rand(1, 12); $human_number2 = rand(1, 38); $human_answer = $human_number1 + $human_number2; $_SESSION['check_answer'] = $human_answer; } if(isset($_POST['Submit'])) { if (!isset($_SESSION['check_answer'])) { echo "<p>Error: Answer session not set</p>"; } if($_POST['math'] != $_SESSION['check_answer']) { echo "<p>You did not pass the human check.</p>"; exit(); } $validator = new FormValidator(); $validator->addValidation("FirstName","req","Please fill in FirstName"); $validator->addValidation("LastName","req","Please fill in LastName"); $validator->addValidation("UserName","req","Please fill in UserName"); $validator->addValidation("Password","req","Please fill in a Password"); $validator->addValidation("Password2","req","Please re-enter your password"); $validator->addValidation("Password2","eqelmnt=Password","Your passwords do not match!"); $validator->addValidation("email","email","The input for Email should be a valid email value"); $validator->addValidation("email","req","Please fill in Email"); $validator->addValidation("Zip","req","Please fill in your Zip Code"); $validator->addValidation("Security","req","Please fill in your Security Question"); $validator->addValidation("Security2","req","Please fill in your Security Answer"); if($validator->ValidateForm()) { $con = mysql_connect("localhost","uname","pw") or die('Could not connect: ' . mysql_error()); mysql_select_db("beatthis_beatthis") or die(mysql_error()); $FirstName=mysql_real_escape_string($_POST['FirstName']); //This value has to be the same as in the HTML form file $LastName=mysql_real_escape_string($_POST['LastName']); //This value has to be the same as in the HTML form file $UserName=mysql_real_escape_string($_POST['UserName']); //This value has to be the same as in the HTML form file $Password= md5($_POST['Password']); //This value has to be the same as in the HTML form file $Password2= md5($_POST['Password2']); //This value has to be the same as in the HTML form file $email=mysql_real_escape_string($_POST['email']); //This value has to be the same as in the HTML form file $Zip=mysql_real_escape_string($_POST['Zip']); //This value has to be the same as in the HTML form file $Birthday=mysql_real_escape_string($_POST['Birthday']); //This value has to be the same as in the HTML form file $Security=mysql_real_escape_string($_POST['Security']); //This value has to be the same as in the HTML form file $Security2=mysql_real_escape_string($_POST['Security2']); //This value has to be the same as in the HTML form file $sql="INSERT INTO Profile (`FirstName`,`LastName`,`Username`,`Password`,`Password2`,`email`,`Zip`,`Birthday`,`Security`,`Security2`) VALUES ('$FirstName','$LastName','$UserName','$Password','$Password2','$email','$Zip','$Birthday','$Security','$Security2')"; //echo $sql; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } else{ mail('email@gmail.com','A profile has been submitted!',$FirstName.' has submitted their profile',$body); echo "<h3>Your profile information has been submitted successfully.</h3>"; } mysql_close($con); $show_form=false; } else { echo "<h3 class='ErrorTitle'>Validation Errors:</h3>"; $error_hash = $validator->GetErrors(); foreach($error_hash as $inpname => $inp_err) { echo "<p class='errors'>$inpname : $inp_err</p>\n"; } } } if(true == $show_form) { ?> Advance thank you. Can you help please. The error..... Warning: mysql_fetch_assoc() expects parameter 1 to be resource, string given in C:\wamp\www\test_dabase.php on line 24 code. Code: [Select] <?php //database connection. $DB = mysql_connect("localhost","root") or die(mysql_error()); if($DB){ //database name. $DB_NAME="mysql"; //select database and name. $CON=mysql_select_db($DB_NAME,$DB)or die(mysql_error()."\nPlease change database name"); // if connection. }if($CON){ //show tables. $mysql_show="SHOW TABLES"; //select show and show. $mysql_select2="mysql_query(".$mysql_show.") or die(mysql_error())"; } //if allowed to show. if($mysql_select2){ //while it and while($data=mysql_fetch_assoc($mysql_select2)){ //show it. echo $data; } } ?> hey gurus, i am a newbie php coder.. i am learning by example. what i am trying to do is write a piece of code which will alter 3 tables (user, bonus_credit, bonus_credit_usage) ---------------------------------------------------------------- the table structure that will be used is as follows: user.bonus_credit user.ID bonus_credit.bonusCode bonus_credit.qty bonus_credit.value bonus_credit_usage.bonusCode bonus_credit_usage.usedBy ---------------------------------------------------------------- so lets say, in bonus_credit i have the following bonusCode = 'facebook' (this is the code they have to type to redeem the bonus qty = '10' ( number of times the bonusCode can be redeemed, but same person can't redeem it more than once) value = '5' (this is the amount of bonus_credit for each qty) Now, I need to write a code that check to see if the code has been redeemed in the bonus_credit_usage table and if the user.ID exists in this table as bonus_code_usage.usedBy, then give an error that its already been used and if it hasn't been used, then subtract 1 from qty, add ID to usedBy and then add the value to the bonus_credit ----------------------- i have started the steps just to create a simple textbox and entering a numeric value to bonus_credit, and that works.. but now i have to use JOIN and IF and ELSE.. which is a little too advanced for me.. so i'd appreciate a guide as i write the code. if(isset($_REQUEST['btnBonus'])) { $bonus_credit = addslashes($_REQUEST['bonusCode']); $query = "update user set bonus_credit=bonus_credit+'".$bonus_credit."' where id='".$_SESSION['SESS_USERID']."'"; echo "<script>window.location='myreferrals.php?msgs=2';</script>"; mysql_query($query) or die(mysql_error()); } I use this type of a code to send automatic emails from my website: Code: [Select] $headers = ; $headers .= ; $to = ; Click here to go to Google. ", $headers); I am having hard time figuring out how to do hyperlink on words (like here). If I do something like this: Code: [Select] <a href='http://www.google.com'>here</a> it spits out that exact thing out. Thanks you for your input Can you help me integrate this code :
<form method="post" action="submit.php"> <input type="checkbox" class="required" /> Click to check <br /> <input disabled="disabled" type='submit' id="submitBtn" value="Submit"> </form>In to this Contact Form code, please? <form action="../page.php?page=1" method="post" name="contact_us" onSubmit="return capCheck(this);"> <table cellpadding="5" width="100%"> <tr> <td width="10" class="required_field">*</td> <td width="80">Your Name</td> <td><input type="text" name="name" maxlength="40" style="width:400px;/></td> </tr> <tr> <td class="required_field">*</td> <td>Email Address</td> <td><input type="text" name="email" maxlength="40" style="width:400px;/></td> </tr> <tr> <td></td> <td>Comments:</td> <td><textarea name="comments" style="width: 400px; height: 250px;"></textarea></td> </tr> </table> </form Hi, Look at this code below: Code: [Select] <?php function outputModule($moduleID, $moduleName, $sessionData) { if(!count($sessionData)) { return false; } $markTotal = 0; $markGrade = 0; $weightSession = 0; $grade = ""; $sessionsHTML = ""; foreach($sessionData as $session) { $sessionsHTML .= "<p><strong>Session:</strong> {$session['SessionId']} <strong>Session Mark:</strong> {$session['Mark']}</strong> <strong>Session Weight Contribution</strong> {$session['SessionWeight']}%</p>\n"; $markTotal += round($session['Mark'] / 100 * $session['SessionWeight']); $weightSession += ($session['SessionWeight']); $markGrade = round($markTotal / $weightSession * 100); if ($markGrade >= 70) { $grade = "A"; } else if ($markGrade >= 60 && $markGrade <= 69) { $grade = "B"; } else if ($markGrade >= 50 && $markGrade <= 59) { $grade = "C"; } else if ($markGrade >= 40 && $markGrade <= 49) { $grade = "D"; } else if ($markGrade >= 30 && $markGrade <= 39) { $grade = "E"; } else if ($markGrade >= 0 && $markGrade <= 29) { $grade = "F"; } $moduleHTML = "<p><br><strong>Module:</strong> {$moduleID} - {$moduleName} <strong>Module Mark:</strong> {$markTotal} <strong>Mark Percentage:</strong> {$markGrade} <strong>Grade:</strong> {$grade} </p>\n"; return $moduleHTML . $sessionsHTML; } $output = ""; $studentId = false; $courseId = false; $moduleId = false; while ($row = mysql_fetch_array($result)) { if($studentId != $row['StudentUsername']) { //Student has changed $studentId = $row['StudentUsername']; $output .= "<p><strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']})\n"; } if($courseId != $row['CourseId']) { //Course has changed $courseId = $row['CourseId']; $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <strong>Course Mark</strong> <strong>Grade</strong> <br><strong>Year:</strong> {$row['Year']} </p>\n"; } if($moduleId != $row['ModuleId']) { //Module has changed if(isset($sessionsAry)) //Don't run function for first record { //Get output for last module and sessions $output .= outputModule($moduleId, $moduleName, $sessionsAry); } //Reset sessions data array and Set values for new module $sessionsAry = array(); $moduleId = $row['ModuleId']; $moduleName = $row['ModuleName']; } //Add session data to array for current module $sessionsAry[] = array('SessionId'=>$row['SessionId'], 'Mark'=>$row['Mark'], 'SessionWeight'=>$row['SessionWeight']); } //Get output for last module $output .= outputModule($moduleId, $moduleName, $sessionsAry); //Display the output echo $output; } } } ?> This code allallows me to make calculations and display a student's course and linked with it the course the modules in the course and linked with modules are all the sessions. It is able to display what marks each student have got for each module and session. Now look at code below, it is able to display modules and in those modules the sessions that link to those modules: Code: [Select] <?php if($moduleId != $row['ModuleId']) { //Module has changed if(isset($sessionsAry)) //Don't run function for first record { //Get output for last module and sessions $output .= outputModule($moduleId, $moduleName, $sessionsAry); } //Reset sessions data array and Set values for new module $sessionsAry = array(); $moduleId = $row['ModuleId']; $moduleName = $row['ModuleName']; } //Add session data to array for current module $sessionsAry[] = array('SessionId'=>$row['SessionId'], 'Mark'=>$row['Mark'], 'SessionWeight'=>$row['SessionWeight']); } What I want to know is how can I do something similar for course so that it picks out the right modules depending on the course it displays. There maybe some code that needs to be added in the function. Can I combine also HTML code in PHP function? For example, can a PHP function include HTML form and the PHP code to handle this form? If yes, this will make my main code much more smaller and readable. If not, is there a way to define an "external macro" like, which allow me to replace pre-defined lines of code with short alias? Alright so I'm attempting to save config data via php. Bellow is the code I currently have, however I'm afraid that when I "flip the switch" and use it that it will error out because of the <?php and ?> tags inside of it... Ideas, suggestions? $config = '../includes/config.php'; $fh = fopen($config, 'w'); $data = ' <?php $dbhost = "'.$database_host.'"; $dbuser = "'.$database_username.'"; $dbpass = "'.$database_password.'"; $dbname = "'.$database_name.'"; $key = "'.$site_key.'"; $cron_key = "'.$database_cron_key.'"; ?> '; fwrite($fh, $data); fclose($fh); Michael Feathers coined the term Legacy Code as being code without automated tests.
Still however Legacy Code evokes a vision in me that it is code that is ugly, old, runs on mainframes, and is probably 3000 lines long, uses globals and questionable code practices.
But say we take this ugly nasty code, and put it very nicely under test, but without doing any refactoring, other than that necessary to be able to put it under test in the first place.
Now that code is under test. But it it still ugly. How would you call ugly code under test?
Would you make a differentiation between old & ugly and modern & pretty code if both are under test?
Hi, this is my first time posting here. I am just delving into PHP and I am learning about foreach loops. I have written code in Notepad++ EXACTLY the way I saw it in a tutorial video I watched (I wish I could show the tutorial video to you, but it is on Lynda.com and you have to pay to watch) I attached the file with my code. The example 1 code works just fine. The example 2 code is the one that is not working for some reason. However, it worked for the guy that wrote it in the video, so I am not sure where I am going wrong? *The comments in green are mainly for myself, I explain things to myself so that I don't forget what the code does forloops.php 1.74KB 2 downloads I would appreciate some help. Thank you!!! |