PHP - New To Php, Is There A Way To Simplify This Code?
I'm sure there must be a way to simplify code as it is taking forever. The code is for a form with the results emailed to me.
I have attached the files as they are too big to post here Similar TutorialsSay I am running multiple contests at the same time. Each contest may have a different end date. One contest might run for a day, while the other one might run for 5 days. Below is the code done my way. I was wondering how you can improve it to make it more efficient? $current_date = date('Y-m-d H:i:s'); $find_contest = $db->prepare("SELECT days_count, date_started FROM contests WHERE status = :status"); $find_contest->bindValue(':status', 1); $find_contest->execute(); $result_contest = $find_contest->fetchAll(PDO::FETCH_ASSOC); if(count($result_contest) > 0) { foreach($result_contest as $row) { $days_count = $row['days_count']; // NUMBER OF DAYS THE CONTEST IS RUNNING $date_started = $row['date_started']; // START DATE FOR THE CONTEST $date_1 = DateTime::createFromFormat('Y-m-d H:i:s',$date_started); $date_1->modify('+1 day'); $end_date_1 = $date_1->format('Y-m-d H:i:s'); $date_2 = DateTime::createFromFormat('Y-m-d H:i:s',$date_started); $date_2->modify('+2 days'); $end_date_2 = $date_2->format('Y-m-d H:i:s'); $date_3 = DateTime::createFromFormat('Y-m-d H:i:s',$date_started); $date_3->modify('+3 days'); $end_date_3 = $date_3->format('Y-m-d H:i:s'); if($days_count == 1) { if($current_date > $end_date_1 AND $current_date < $end_date_2) { $day = 1; $end_date = $end_date_1; require 'run-contest.php'; } } else if($days_count == 2) { if($current_date > $end_date_1 AND $current_date < $end_date_2) { $day = 1; $end_date = $end_date_1; require 'run-contest.php'; } else if($current_date > $end_date_2 AND $current_date < $end_date_3) { $day = 2; $end_date = $end_date_2; require 'run-contest.php'; } else {} } else {} } }
Hi ? I wrote a PHP code but I think i can simplify more specially in the switch part , as you can see in the code. can you please give me some advise. <form method="post" action="<?=$_SERVER['PHP_SELF'];?>"> <fieldset> X: <input type="text" name="x" value="" /> <br/> Y: <input type="text" name="y" value="" /> <br/> <select name="diametre"> <option value=" "> </option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="6">6</option> <option value="8">8</option> <option value="10">10</option> <option value="12">12</option> <option value="14">14</option> <option value="16">16</option> <option value="18">18</option> <option value="20">20</option> <option value="22">22</option> <option value="24">24</option> <option value="26">26</option> </select> <input type="submit" value = "Calculer" /> </fieldset> </form> <?php if (isset($_POST["x"]) && isset($_POST["y"]) && isset($_POST["diametre"]) ){ $x = $_POST["x"]; $y = $_POST["y"]; $diametre = $_POST["diametre"]; } switch ($diametre) { case "2": $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; echo "X = " . $x . "mm" . "<br/>"; echo "Y = " . $y . "mm" . "<br/>"; echo "Longueur = " . number_format($LongueurBayonette,1) . " mm" . "<br/>"; echo "ꞵ = " . number_format($angle,1) . "°" . "<br/>"; echo "Rayon = " . $rayon . " mm" . "<br/>"; echo "⌀ = " . $diametre . '"' . "<br/>"; break; case "3": $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; echo "X = " . $x . "mm" . "<br/>"; echo "Y = " . $y . "mm" . "<br/>"; echo "Longueur = " . number_format($LongueurBayonette,1) . "mm" . "<br/>"; echo "ꞵ = " . number_format($angle,1) . "°" . "<br/>"; echo "Rayon = " . $rayon . "mm" . "<br/>"; echo "⌀ = " . $diametre . '"' . "<br/>"; break; case "4": $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; echo "X = " . $x . "mm" . "<br/>"; echo "Y = " . $y . "mm" . "<br/>"; echo "Longueur = " . number_format($LongueurBayonette,1) . "mm" . "<br/>"; echo "ꞵ = " . number_format($angle,1) . "°" . "<br/>"; echo "Rayon = " . $rayon . "mm" . "<br/>"; echo "⌀ = " . $diametre . '"' . "<br/>"; break; case "6": $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; echo "X = " . $x . "mm" . "<br/>"; echo "Y = " . $y . "mm" . "<br/>"; echo "Longueur = " . number_format($LongueurBayonette,1) . "mm" . "<br/>"; echo "ꞵ = " . number_format($angle,1) . "°" . "<br/>"; echo "Rayon = " . $rayon . "mm" . "<br/>"; echo "⌀ = " . $diametre . '"' . "<br/>"; break; case "8": $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; echo "X = " . $x . "mm" . "<br/>"; echo "Y = " . $y . "mm" . "<br/>"; echo "Longueur = " . number_format($LongueurBayonette,1) . "mm" . "<br/>"; echo "ꞵ = " . number_format($angle,1) . "°" . "<br/>"; echo "Rayon = " . $rayon . "mm" . "<br/>"; echo "⌀ = " . $diametre . '"' . "<br/>"; break; case "10": $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; echo "X = " . $x . "mm" . "<br/>"; echo "Y = " . $y . "mm" . "<br/>"; echo "Longueur = " . number_format($LongueurBayonette,1) . "mm" . "<br/>"; echo "ꞵ = " . number_format($angle,1) . "°" . "<br/>"; echo "Rayon = " . $rayon . "mm" . "<br/>"; echo "⌀ = " . $diametre . '"' . "<br/>"; break; case "12": $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; echo "X = " . $x . "mm" . "<br/>"; echo "Y = " . $y . "mm" . "<br/>"; echo "Longueur = " . number_format($LongueurBayonette,1) . "mm" . "<br/>"; echo "ꞵ = " . number_format($angle,1) . "°" . "<br/>"; echo "Rayon = " . $rayon . "mm" . "<br/>"; echo "⌀ = " . $diametre . '"' . "<br/>"; break; case "14": $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; echo "X = " . $x . "mm" . "<br/>"; echo "Y = " . $y . "mm" . "<br/>"; echo "Longueur = " . number_format($LongueurBayonette,1) . "mm" . "<br/>"; echo "ꞵ = " . number_format($angle,1) . "°" . "<br/>"; echo "Rayon = " . $rayon . "mm" . "<br/>"; echo "⌀ = " . $diametre . '"' . "<br/>"; break; case "16": $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; echo "X = " . $x . "mm" . "<br/>"; echo "Y = " . $y . "mm" . "<br/>"; echo "Longueur = " . number_format($LongueurBayonette,1) . "mm" . "<br/>"; echo "ꞵ = " . number_format($angle,1) . "°" . "<br/>"; echo "Rayon = " . $rayon . "mm" . "<br/>"; echo "⌀ = " . $diametre . '"' . "<br/>"; break; case "18": $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; echo "X = " . $x . "mm" . "<br/>"; echo "Y = " . $y . "mm" . "<br/>"; echo "Longueur = " . number_format($LongueurBayonette,1) . "mm" . "<br/>"; echo "ꞵ = " . number_format($angle,1) . "°" . "<br/>"; echo "Rayon = " . $rayon . "mm" . "<br/>"; echo "⌀ = " . $diametre . '"' . "<br/>"; break; case "20": $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; echo "X = " . $x . "mm" . "<br/>"; echo "Y = " . $y . "mm" . "<br/>"; echo "Longueur = " . number_format($LongueurBayonette,1) . "mm" . "<br/>"; echo "ꞵ = " . number_format($angle,1) . "°" . "<br/>"; echo "Rayon = " . $rayon . "mm" . "<br/>"; echo "⌀ = " . $diametre . '"' . "<br/>"; break; case "22": $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; echo "X = " . $x . "mm" . "<br/>"; echo "Y = " . $y . "mm" . "<br/>"; echo "Longueur = " . number_format($LongueurBayonette,1) . "mm" . "<br/>"; echo "ꞵ = " . number_format($angle,1) . "°" . "<br/>"; echo "Rayon = " . $rayon . "mm" . "<br/>"; echo "⌀ = " . $diametre . '"' . "<br/>"; break; case "24": $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; echo "X = " . $x . "mm" . "<br/>"; echo "Y = " . $y . "mm" . "<br/>"; echo "Longueur = " . number_format($LongueurBayonette,1) . "mm" . "<br/>"; echo "ꞵ = " . number_format($angle,1) . "°" . "<br/>"; echo "Rayon = " . $rayon . "mm" . "<br/>"; echo "⌀ = " . $diametre . '"' . "<br/>"; break; case "26": $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; echo "X = " . $x . "mm" . "<br/>"; echo "Y = " . $y . "mm" . "<br/>"; echo "Longueur = " . number_format($LongueurBayonette,1) . "mm" . "<br/>"; echo "ꞵ = " . number_format($angle,1) . "°" . "<br/>"; echo "Rayon = " . $rayon . "mm" . "<br/>"; echo "⌀ = " . $diametre . '"' . "<br/>"; break; default: echo " "; } ?> The result is this page: http://cadtuts.eu/bayonette-test.php
Thank you ?
This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=315554.0 Hello! I have this approach on form validation(I'm just a newbie) Code: [Select] <?php if(isset($_POST['submit'])) { $proj_name = me_mysql_prep(trim($_POST['proj_name'])); $proj_content = me_mysql_prep($_POST['proj_content']); if(empty($_POST['proj_name'])) { $empty_name = array('Project Name Cannot Be Empty'); } if(empty($_POST['proj_content'])) { $empty_content = array('Content Cannot Be Empty'); } if(isset($empty_name) || isset($empty_content)); { $error_merge = array_merge($empty_name, $empty_content); } if(!empty($error_merge)) { foreach($error_merge as $error) { echo "<span class=\"error_validation\">*". $error . "<br></span>"; } } else { $query = "INSERT into rec_projects (proj_name, content, date_reg) VALUES('{$proj_name}', '{$proj_content}', '{$datenow}')"; $result = mysql_query($query,$connection); } echo "<br><br>"; } ?> My problem is at this line Code: [Select] <?php if(isset($empty_name) || isset($empty_content)); { $error_merge = array_merge($empty_name, $empty_content); } ?> because if, let's say $empty_name is not set, I'm going to have an error like Quote "undefined $empty_name" or something like that. I wonder if there's a PHP function that disregard a value in an array if it's not set.. or you guys have different approach to solve and simplify this?? 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 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>"; } ?> 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()); } 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) { ?> 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. 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 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?
Hello Everyone I am new to php and indeed Web Development. After testing and Playing a bit, I can get the following code to work as two files, the form calling the *.php file to insert into the database, however, I am trying to create one html/php file that displays the form and then executes the php code to insert into the database once user clickes the button. Please can you assist me with the code? I have something horribly wrong and I cannot find it. Code: [Select] <?php> <html> <head> <title>Personal Details</title> </head> <body> <form method="post" action="contactdetails.html"><font face="Arial"> Call Sign:<br> <input name="callsign" size="5" type="text"><br> Surame:<br> <input name="surname" size="30" type="text"><br> First Name:<br> <input name="firstnames" size="30" type="text"><br> Known as:<br> <input name="knownas" size="30" type="text"><br> RSA ID No.:<br> <input name="rsaid" size="13" type="text"><br> Birth Date:<br> <input name="birthdate" size="12" type="text"><br> <input name="Insert" value="Next" type="submit"></form> </font><br> </body> </html> //php to insert data into table $callsign = $_POST['callsign']; $surname = $_POST['surname']; $firstnames = $_POST['firstnames']; $knownas = $_POST['knownas']; $rsaid = $_POST['rsaid']; $birthdate = $_POST['birthdate']; mysql_connect ("localhost", "jredpixm_testuse", "PHPDevelopment") or die ('I cannot connect to the database because: ' .mysql_error()); mysql_select_db ("jredpixm_test"); $query="INSERT INTO personal_details (callsign, surname, firstnames, knownas, rsaid, birthdate)Values ('$callsign', '$surname', '$firstnames', '$knownas', '$rsaid', '$birthdate')"; mysql_query($query) or die ('Error updating Database'); echo "<p>Thanks, your information has been added to the database.</p>"; ?> Regards Allen 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!!! How can I make sure that when I submit an new form and new ID (record) is created it is always 4-Digits. record 14 = 0014, record 225 = 0225. Thanks Hello
I am very new to php, in fact I have just really started learning 5 days ago. I have a book, (php3-4) that has got me through the years and if you go through the old posts of mine, you see how bad I really am with php. If you don't mind me having your MSN address so I can randomly ask questions about php, Please add me, gaogier@runehints.com So, this is what the code MUST do, add data to each calculator. The new code is for another section of our CMS. Here is the old code. From our old CMS. //------------------------Begin Calc-------------------------------------------// function calc(){ echo '<p><font class="adminheader">Caclulator Admin</font></p>'; echo "<TABLE border=\"0\" width=\"89%\" class=monster>\n"; echo "<TR><TD class=title><center>Calculator Name</center></td><td class=title><center>Insert - Edit - Delete</center></TD></TR>\n"; /* query for monsters */ $query = "SELECT id, name, members, tablename FROM calc ORDER BY name ASC"; $result = mysql_query ($query); while ($row = mysql_fetch_assoc ($result)) { /* display monsters in a table */ /* place table row data in * easier to use variables. */ $count = $count + 1; $name = $row['name']; $mem = $row['members']; if ($mem == "Y"){ $ignore = 1; }else{ $ignore = 0; } $tablename = $row['tablename']; /* display the data */ echo '<TR bgcolor="'.processRow($count).'"><TD class="calc"><b>'.$name.'</b></td><td class="calc"><a href="'.$_SERVER['PHP_SELF'] . '?flibble=calcitem&calc='.$tablename.'&ignore='.$ignore.'"><img src="images/admin/insert.png" alt="Insert data items" border="0"></a> <a href="'.$_SERVER['PHP_SELF'] . '?flibble=c_update&id='.$row['id'].'&ignore='.$ignore.'"><img src="images/admin/view.gif" alt="Edit" border="0"></a> <a href="'.$_SERVER['PHP_SELF'] . '?flibble=c_delete&id='.$row['id'].'&ignore='.$ignore.'"><img src="images/admin/delete.gif" alt="Delete" border="0"></a></TD></TR>'; if($count == 2){ $count = 0; } } /* finish up table*/ echo "</TABLE>\n"; echo '<p><b><a href="http://runehints.com/admin2.php?flibble=add_c"><img src="images/plus.gif" alt="Add" border="0"> Add calculator</a></b></p>'; } function calcitem($calc){ $calc1 = str_replace("calc", "", $calc); echo '<p><font class="adminheader">Caclulator Item Admin for '.$calc1.'</font></p>'; echo "<TABLE border=\"0\" width=\"89%\" class=monster>\n"; echo "<TR><TD class=title><center>Item Name</center></td><td class=title><center>Level - XP</center></TD><td class=title><center>Edit</center></TD</TR>\n"; /* query for monsters */ $query = "SELECT id, item, members, level, xp FROM ".$calc." ORDER BY level, item ASC"; if(!$result = mysql_query ($query)) die(mysql_error()); while ($row = mysql_fetch_assoc ($result)) { /* display monsters in a table */ /* place table row data in * easier to use variables. */ $count = $count + 1; $name = $row['item']; $mem = $row['members']; if ($mem == "1"){ $ignore = 1; }else{ $ignore = 0; } $tablename = $row['tablename']; $level = $row['level']; $xp = $row['xp']; /* display the data */ echo '<TR bgcolor="'.processRow($count).'"><TD class="calc"><b>'.$name.'</b></td><TD class="calc"><b>'.$level.' - '.$xp.'</b></td><td class="calc"><a href="'.$_SERVER['PHP_SELF'] . '?flibble=edit_citem&calc='.$calc.'&id='.$row['id'].'&ignore='.$ignore.'"><img src="images/admin/view.gif" alt="Edit" border="0"></a> <a href="'.$_SERVER['PHP_SELF'] . '?flibble=c_delete&id='.$row['id'].'"><img src="images/admin/delete.gif" alt="Delete" border="0"></a></TD></TR>'; if($count == 2){ $count = 0; } } $ignores = $_GET['ignore']; /* finish up table*/ echo "</TABLE>\n"; echo '<p><b><a href="http://runehints.com/admin2.php?flibble=add_citem&calc='.$calc.'&ignore='.$ignores.'"><img src="images/plus.gif" alt="Add" border="0"> Add a calculator item</a></b></p>'; } function c_update($id) { /* query for item */ $query = "SELECT * FROM calc WHERE id=$id"; $result = mysql_query ($query); /* if we get no results back, error out */ $numrtn = mysql_num_rows($result); if ($numrtn == 0) { echo "The Skill guide requested cannot be found\n"; return; } $row = mysql_fetch_assoc($result); /* easier to read variables and * striping out tags */ $id = $row['id']; $name = $row['name']; $members = $row['members']; $guideby = $row['calcby']; if (isset($_POST['submit'])){ //handle form require_once ('../mysql_connect.php');//connect to db $name = escape_data($_POST['name']); $members = escape_data($_POST['members']); $calcby = escape_data($_POST['guideby']); if ($name && $members && $calcby){//if evrything is ok $query = "UPDATE calc SET name = '$name' , members = '$members', calcby = '$calcby' WHERE id ='$id'"; $result = @mysql_query ($query); //Run the query. if ($result){ //if it entered correctly echo '<br /><table width=98% bgcolor=#565866 class=pass align=center><tr> <td width=40><img src=images/tick.gif></td> <td align=left> <B>Success</B> <BR> The '.$name.' calculator was successfully updated<br /> </table><br /><br />'; include ('difffooter.inc');//footer exit(); }else{ // didn't work echo '<table width=98% bgcolor=#565866 class=logfail align=center><tr> <td width=40><img src=images/exclamation.gif></td> <td align=left> <B>Update Failed!</B> <BR> The '.$name.' calculator could not be updated <BR>Please Try again later<br /> </table><br /><br />'; } }else{ echo '<table width=98% bgcolor=#565866 class=logfail align=center><tr> <td width=40><img src=images/exclamation.gif></td> <td align=left> <B>Update Failed!</B> <BR> Data missing. <BR>Please enter all information needed and try again<br /> </table><br /><br />'; } } /* display the items */ echo '<br /><center><font class="adminheader">Update Calculator Information</font></center> <br />'; echo '<form action="admin2.php?flibble=c_update&id='.$id.'" method="post">'; echo ' <center> <table class=calc> <tr><td> <table> <tr><td align=right><font class="text2">Calculator:</font></td><td align=left><input type="text" class="text" name="name" size="15" maxlength="30" value="'.$name.'" /></td></tr> <tr><td align=right><font class="text2">By:</font></td><td align=left><input type="text" class="text" name="guideby" value="'.$guideby.'" /></td></tr> <tr><td align=right><font class="text2">Members?:</font></td><td align=left><input type="text" class="text" name="members" size="1" maxlength="1" value="'.$members.'" /><font class="small2">Use Y or N only</font></td></tr> </table> </td> </tr> </table> </CENTER> </form> '; ?> <div align="center"><input type="submit" name="submit" value="Update DB" class="liteoption" /> <input type="reset" name="reset" value="reset" class="liteoption" /></div></form> <?php } function c_delete($id){ $query = "SELECT `name` FROM calc WHERE id=$id"; $result = mysql_query ($query); /* if we get no results back, error out */ $numrtn = mysql_num_rows($result); if ($numrtn == 0) { echo "The calculator requested cannot be found\n"; return; } $row = mysql_fetch_assoc($result); /* easier to read variables and * striping out tags */ $name = $row['name']; if (isset($_POST['yes'])){ //handle form $query = "DELETE FROM `calc` WHERE `id` = ".$id." LIMIT 1"; $result = mysql_query($query); if ($result) { ob_end_clean(); header("http://runehints.com/admin2.php?flibble=calc"); } } echo '<table width=98% bgcolor=#565866 class=logfail align=center><tr> <td width=40><img src=images/exclamation.gif></td> <td align=left> <B>Delete?</B> <BR> Are you sure you want to delete '.$name.' from the database? <BR><br /><form action="admin2.php?flibble=c_delete&id='.$id.'" method="post"><input type="submit" name="yes" value="Yes" class="delete" /> <input name="no" type=button onClick="javascript:history.go(-1)" value="No" class="delete" /></form> </table><br /><br />'; } function add_calc() { if (isset($_POST['submit'])){ //handle form require_once ('../mysql_connect.php');//connect to db $name = escape_data($_POST['name']); $calcby = escape_data($_POST['calcby']); $members = escape_data($_POST['members']); if ($name && $calcby && $members){//if evrything is ok $query = "INSERT INTO calc (name, calcby, members) VALUES ('$name', '$calcby','$members')"; $result = @mysql_query ($query); //Run the query. if ($result){ //if it entered correctly echo '<br /><table width=98% bgcolor=#565866 class=pass align=center><tr> <td width=40><img src=images/tick.gif></td> <td align=left> <B>Success</B> <BR> The '.$name.'\' calculator was successfully added<br /> </table><br /><br />'; include ('difffooter.inc');//footer exit(); }else{ // didn't work echo '<table width=98% bgcolor=#565866 class=logfail align=center><tr> <td width=40><img src=images/exclamation.gif></td> <td align=left> <B>Update Failed!</B> <BR> The '.$name.'\ calculator was could not be added <BR>Please Try again later<br /> </table><br /><br />'; } } } ?> <br /><font class="adminheader"><center>Add Calculator</center></font><br /> Here you can add skill guide to the database. Be sure to give credit properly where it is due!<br /> <form action="admin2.php?flibble=add_c" method="post"><center> <table class=calc> <tr><td> <table> <tr><td align=right><font class="text2">Calculator Name:</font></td><td align=left><input type="text" class="text" name="name" size="15" maxlength="30" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>" /></td></tr> <tr><td align=right><font class="text2">Calculator by:</font></td><td align=left><input type="text" class="text" name="calcby" value="<?php if (isset($_POST['calcby'])) echo $_POST['calcby']; ?>" /></td></tr> <tr><td align=right><font class="text2">Members?:</font></td><td align=left><input type="text" class="text" name="members" size="1" maxlength="1" value="<?php if (isset($_POST['members'])) echo $_POST['members']; ?>" /><font class="small2">Use Y or N only</font></td></tr> </table> </td> </tr> <tr> <td> <div align="center"><input type="submit" name="submit" value="Add Calculator" class="liteoption" /> <input type="reset" name="reset" value="reset" class="liteoption" /></div> </td> </tr> </table> </CENTER> </form> <?php } function addcalcitem($calc){ $ignore = $_GET['ignore']; if (isset($_POST['submit'])){ //handle form require_once ('../mysql_connect.php');//connect to db $name = escape_data($_POST['name']); $level = escape_data($_POST['level']); if ($ignore != 1){ $members = strtoupper(escape_data($_POST['members'])); if ($members == "Y"){ $members =1; }else{ $members =0; } } $xp = escape_data($_POST['xp']); if ($name && $level && $xp){//if evrything is ok $query = "INSERT INTO ".$calc." (item, level, xp, members) VALUES ('$name', '$level', '$xp', '$members')"; $result = mysql_query ($query); //Run the query. if ($result){ //if it entered correctly echo '<br /><table width=98% bgcolor=#565866 class=pass align=center><tr> <td width=40><img src=images/tick.gif></td> <td align=left> <B>Success</B> <BR> The item '.$name.' was successfully added<br /> </table><br /><br />'; include ('difffooter.inc');//footer exit(); }else{ // didn't work echo '<table width=98% bgcolor=#565866 class=logfail align=center><tr> <td width=40><img src=images/exclamation.gif></td> <td align=left> <B>Update Failed!</B> <BR> The item '.$name.' could not be added <BR>Please Try again later<br /> </table><br /><br />'; } } } ?> <br /><font class="adminheader"><center>Add Calculator item</center></font><br /> Here you can add items to calculators. Be sure to give credit properly where it is due!<br /> <?php echo '<form action="'.$_SERVER['PHP_SELF'].'?flibble=add_citem&ignore='.$ignore.'&calc='.$calc.'" method="post"><center>'; ?> <table class=calc> <tr><td> <table> <tr><td align=right><font class="text2">Item name:</font></td><td align=left><input type="text" class="text" name="name" size="15" maxlength="30" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>" /></td></tr> <tr><td align=right><font class="text2">Level:</font></td><td align=left><input type="text" class="text" name="level" value="<?php if (isset($_POST['level'])) echo $_POST['level']; ?>" /></td></tr> <tr><td align=right><font class="text2">XP(to decimal if possible):</font></td><td align=left><input type="text" class="text" name="xp" value="<?php if (isset($_POST['xp'])) echo $_POST['xp']; ?>" /></td></tr> <?php if ($ignore !=1){ echo '<tr><td align=right><font class="text2">Members?:</font></td><td align=left><input type="text" class="text" name="members" size="1" maxlength="1" value="'.$_POST['members'].'" /><font class="small2">Use Y or N only</font></td></tr> '; } ?> </table> </td> </tr> <tr> <td> <div align="center"><input type="submit" name="submit" value="Add Calculator item" class="liteoption" /> <input type="reset" name="reset" value="reset" class="liteoption" /></div> </td> </tr> </table> </CENTER> </form> <?php } function editcalcitem($calc){ $ignore = $_GET['ignore']; $id = $_GET['id']; /* query for item */ $query = "SELECT * FROM ".$calc." WHERE id='$id'"; $result = mysql_query ($query); /* if we get no results back, error out */ $numrtn = mysql_num_rows($result); if ($numrtn == 0) { echo "The calculator item requested cannot be found\n"; return; } $row = mysql_fetch_assoc($result); /* easier to read variables and * striping out tags */ $name = $row['item']; $members = $row['members']; if ($members == "1"){ $members ="Y"; }else{ $members ="N"; } $xp = $row['xp']; $level = $row['level']; $ignore = $_GET['ignore']; if (isset($_POST['submit'])){ //handle form require_once ('../mysql_connect.php');//connect to db $name = escape_data($_POST['name']); $level = escape_data($_POST['level']); if ($ignore != 1){ $members = strtoupper(escape_data($_POST['members'])); if ($members == "Y"){ $members =1; }else{ $members =0; } } $xp = escape_data($_POST['xp']); if ($name && $level && $xp){//if evrything is ok $query = "UPDATE ".$calc." SET item = '$name', level = '$level', xp = '$xp' , members='$members' WHERE id='$id'"; $result = @mysql_query ($query); //Run the query. if ($result){ //if it entered correctly echo '<br /><table width=98% bgcolor=#565866 class=pass align=center><tr> <td width=40><img src=images/tick.gif></td> <td align=left> <B>Success</B> <BR> The item '.$name.'\' was successfully added<br />
|