PHP - Code Optimization
Hi all.
I was looking for some tips on code optimization and came across a few resources. However, I know nothing as of yet about code optimization so I'm not sure how legitimate these resources are. Some confirmation would be very helpful along with any personal tips you may have. Thanks in advance! http://www.wmtips.com/php/tips-optimizing-php-code.htm http://www.chazzuka.com/blog/?p=58(some redundancy from the first link is included here) Some Questions I Thought Up (Warning: may be ridiculous questions): 1) Does excess white space (returns, space, tabs, etc.) in files affect performance for a large scale application (For an application that's ~500 files)? 2) Does directory structure affect performance (e.g. 3 directories deep versus 10 directories deep)? Possibly more to come Similar TutorialsThis is a two parter... mostly a discussion as I am currently not employing the purpose of these "things"
I am creating an autoparsing webapp that has unlimited use... whatever a person can think of
It accesses camera, microphone, gyro/accelerometer, flash etc... mostly it takes in data and does something to it according to the parsing tool
I'm not saying this is new, in fact I spent a while using Touch Develop which is a scripting "thing" by Microsoft, the problem was lag
That is another thing that concerns me, without web access the web-app is useless right? So I'm wondering if it is possible to copy your current setup and either translate it to the mobile languages like Java, C#/XML, Objective C or somehow a platform independent alternative
Anyway...
I'm not sure if I can access front end code, like <div class="whatever"> safely using injection
Well injection you just bind parameters but what if the incoming string is literally malicious ?
Also as far as autoparsing optimization goes, what I mean by that is
I intended to create a character by character comparison, obviously or at least to me, starting with easier stuff first like
for example a link is entered
http://www.something.com
then the autoparser compares each character one at a time from left to right
|1|2|3|4|5|6|7|8|9|10|
|h|t|t|p|:|/|/|w|w|w|...etc...
But I would check for existing formats starting with the shortest first and also checking from right and left, eg. .mp4 is obvious as a file type
I'll have more once I actually know what I need just looking to discuss I suppose... sorry if that is not appropriate feel free to delete this thread
In the future the users who have modified their personal accounts would benefit from an "AI" thing that is specific to their personalities based on what they have enabled
Edited by greenace92, 28 December 2014 - 09:37 AM. i have a random no. of directories and files being created using the mkdir and touch functions and the newly created files are copying a pre-made template.. the links of the pages which were being created had %20 signs between the spaces.. i wanted to change them with "-" soo i used the following code.. but it gives errors.. as invalid arguments in mkdir and touch and as well as copy function can anyone help? here is the code while ($row = mysql_fetch_assoc($result1) ) { $hosting = explode(',', $row['host']); $linking = explode(',', $row['links']); $parts = explode(',', $row['link_no']); $no_host = count($hosting); //miniusing the no of loops to make it accurate $count_host = count($hosting); $count_links = count($parts); $current_k = 0; $sum = 0; $parts_href = ''; $new = null; $updated_part = null; for($i=0; $i<($count_host-1); $i++ ) { $j = $i+1; $hos = str_replace(":","",$hosting[$i]); $path = "$base_folder/{$hos}"; echo "<br />{$hos}"; echo "<br />{$path}"; mkdir($path); for($k=$current_k; $k<($count_links); $k++) { for($f=0; $f<$parts[$current_k]; $f++ ) { $for_touch = "$base_folder/{$hos}/".$linking[$sum].".php"; $for_touch = str_replace(" ","-",$for_touch); touch("$for_touch"); $new_seo = "{$part_href}/{$hos}/".$linking[$sum].".php"; $new_seo = str_replace(" ","-",$new_seo); $new = "$new_seo"; $updated_part = $updated_part.$new; $updated_part = $updated_part.","; //copy function $old_file = "$for_touch"; $new_file = "{$part_page}/part".$sum.".php"; $new_file = str_replace(" ","-",$new_file); $new_file = "$new_file"; copy($new_file,$old_file); $sum++; } $query_href = 'update movies set href_parts = \''.$updated_part.'\''; mysql_query($query_href) or die('COULD NOT EXECUTE THE QUERY FOR PARTS HREF'); echo "<br />{$updated_part}"; $sum = $sum; $current_k = $current_k+1; break; } } PLEASE HELP ME! I am trying to optimize my website for speed as much as possible. However it is heavily database driven. Are there any ways to speed up each page request? Also I am closing each MySql connection after every page load. Here is my database class, is that a good idea? <?php //For changes, see: http://www.php.net/manual/en/mysqli.connect.php class Database{ var $mysqli, $result, $q, $affectedRows; function __construct($host, $user, $pass, $db){ $this->connect($host, $user, $pass, $db); } function connect($host, $user, $pass, $db){ $this->mysqli = new MySQLi($host, $user, $pass, $db); if(mysqli_connect_error()){ //Add Line to error handling system here... echo "Internal Site Error - Cannot Continue!"; exit; } } function clean(){ $str = $this->q; $str = @trim($str); if(get_magic_quotes_gpc()){ $str = stripslashes($str); } $this->q = mysqli_real_escape_string($this->mysqli, $str); } function execute($query, $mode = MYSQLI_STORE_RESULT){ $this->q = $query; $this->clean(); $result = $this->mysqli->query($query, $mode); if(is_object($result) && $result instanceof MySQLi_Result){//if result is a object and is part of the mysqli class? $this->result = $result; $this->affectedRows = $this->result->num_rows; }else $this->affectedRows = $this->mysqli->affected_rows; return $this; } function fetchRow(){ return $this->result->fetch_assoc(); } function fetchAll(){ /*$row = $this->result->fetch_all($mode); See manual for the mode under mysqli_result::fetch_all //return !empty($row) ? $row : array();//if not empty return row, else return an array? */ $row = array(); while($f = $this->fetchRow()){ $row[] = $f; } return !empty($row) ? $row : array(); } function numRows(){ return $this->affectedRows; } function delete($table, $where){ return $this->execute("DELETE FROM ".$table." WHERE ".$where); } function deleteAll($table){ return $this->execute("TRUNCATE ".$table); } function update($table, $set, $where){ return $this->execute("UPDATE ".$table." SET ".$set." WHERE ".$where); } function select($table, $select = "*", $where = NULL, $cap = ""){ if(is_null($where) || empty($where)) return $this->execute("SELECT ".$select." FROM ".$table." ".$cap); else return $this->execute("SELECT ".$select." FROM ".$table." WHERE ".$where." ".$cap); } function lastId(){ return $this->mysqli->insert_id; } function resetInc($table, $inc){ $this->execute("ALTER TABLE ".$table." AUTO_INCREMENT = ".$inc); } function error(){ return @mysqli_error($this->mysqli). " <strong><font color=\"red\">QUERY</font>: ".$this->q."</strong>"; } function close(){ @mysqli_close($this->mysqli); } function __destruct(){ $this->close(); } } $db = new Database(DB_HOST, DB_USER, DB_PASS, DB_DB); ?> This topic has been moved to PHP Freelancing. http://www.phpfreaks.com/forums/index.php?topic=346599.0 I am using a PHP include file for my site, which includes validation functions used throughout out the site. Like string type, alphanumeric values, etc. Its completely customized for the types of user inputs the site takes. The problem is, each page uses only about 2-3 functions from the whole list of 16. One of the pages gives a memory_get_usage() of 748KB. If I remove the Inluded file, it goes down by 200KB. While the include file is of 4KB and the test page is 2KB. I am looking for a method to optimize the memory allocation. I dont want to write the code separately for each file.Is there a method to optimize for uncalled functions? Thanks in Advance. Thank you for looking into this! I need to use result from mysql query twice or more on a page Should I do this: $sql = mysql_query("SQL"); while ($row = mysql_fetch_assoc($sql)) CODE ... while ($row = mysql_fetch_assoc($sql)) CODE2 OR should I keep result of a query in an array and use FOREACH instead? My concern is performance. Hi I am presently writing a code which does the following steps given a site 1) get some keywords (written a function for it) 2) search google for these keywords (I have used curl and getURL functions for these) 3) perform keyword search in the first page of googles results. Presently I have used curl and curl_multi_getcontent but when i run the code it consumes 100% of my server. My server will not respond in this case if someone else pings. I have been trying to do pcntl_fork, but could you let me know how to optimize this code by threading and forking. I am a newbe in PHP please let me know the structure of how to invoke multiple threads and process the same. If you have someother suggestions please let me know that too. Can someone please double check my search query to make sure it is the minimum and most efficient coding. My goal is an exact match search of field1 from my database table and list field1, field2, field3, field4 and field5 if the part number is in the database or no results if it is not. The query works as is but I have a feeling it could be done more efficiently or professionally and minimum work for my poor little server. Thanks in advance. Code: [Select] <?php //connect to the database include("./databaseconnect.php"); //get query $q=$_GET['q']; //convert query to uppercase & remove all spaces and special charactars $q=strtoupper(preg_replace("/[^A-Za-z0-9]/","",$q)); //if blank query if ($q == "") { echo "You did not enter a search term"; } else { //exact match only query $query = "SELECT * FROM ".$dbtable." WHERE field1 like \"$q\""; $result = mysql_query($query); //if query returns no results if(mysql_num_rows($result)==0) { echo "<span class=\"noresults\">There were no results for your search</span>"; //display database results } else { while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "<span class=\'results\'>SEARCH RESULTS</span><br /> <span class=\'list\'>Part Number: ".$row['field1']."<br /> Manufacturer: ".$row['field2']."<br /> Cost per unit: ".$row['field3']."<br /> Warehouse Location: ".$row['field4']."<br /> Quantity Available: ".$row['field5']."<br /> Notes: ".$row['field6']."<br /> </span>"; } } } ?> Hi Guys and Gals, I run a simple fansite for some of my fellow MTG Tactics players at www.onlinegamekey.com I recently made a Booster Page value page he http://www.onlinegamekey.com/booster-packs.php And it seems the page loads really slow, but I kind of understand that since its doing a lot of math and dealing with a lot of data. I am wondering if there is a way to possibly optimize the page and querys in such a way that it doesn't take so long to load. I'm basically using 4 queries to get the value of each pack and 1 function to average the query data. And I add them up as I go. This is my function to find average values Code: [Select] ///AVERAGE FUNCTION function calculate_average($arr) { $count = count($arr); //total numbers in array foreach ($arr as $value) { $total = $total + $value; // total value of array numbers } $average = ($total/$count); // get average value return $average; } These are the queries to get the Average Values Code: [Select] <?php ///SETTING THE DAY $today = date("Y/m/d"); ///ALTERING DAY QUERY TIME (20 Days of Data) $minusday = mktime(0,0,0,date("m"),date("d")-20,date("Y")); ///SETTING THE DAY FOR THE QUERIES $queryday = date("Y/m/d",$minusday); ///DATA SET FOR BOOSTER PACK 1 //GET THE MYTHIC AVERAGE VALUE $sqlMythic=mysql_query("SELECT AVG( ab.Price_Per ) AS Aaverage FROM auctions AS ab INNER JOIN cardlist AS c ON c.card_name = ab.Card_Name WHERE ab.Day >= '$queryday' AND c.rarity = 'Mythic Rare' AND c.set = '1' GROUP BY c.card_name, ab.Card_Name") or die; while ($row=mysql_fetch_array($sqlMythic)) { $MythicValues[]=$row['Aaverage']; } ///MYTHIC VALUE IS 10% OF AVERAGE VALUE $Mythic = calculate_average($MythicValues) * .1; //GET THE RARE AVERAGE VALUE $sqlRare=mysql_query("SELECT AVG( ab.Price_Per ) AS Aaverage FROM auctions AS ab INNER JOIN cardlist AS c ON c.card_name = ab.Card_Name WHERE ab.Day >= '$queryday' AND c.rarity = 'Rare' AND c.set='1' GROUP BY c.card_name, ab.Card_Name") or die; while ($row=mysql_fetch_array($sqlRare)) { $RareValues[]=$row['Aaverage']; } ///RARE VALUE IS 90% OF AVERAGE RARE VALUE $Rare = calculate_average($RareValues) *.9; ///TOTAL CONTRIBUTION TO PACK 100% IS 10% MYTHIC + 90% RARE $raremythic= $Mythic + $Rare; ///GET THE UNCOMMON AVERAGE VALUE $sqlUncommon=mysql_query("SELECT AVG( ab.Price_Per ) AS Aaverage FROM auctions AS ab INNER JOIN cardlist AS c ON c.card_name = ab.Card_Name WHERE ab.Day >= '$queryday' AND c.rarity = 'Uncommon' AND c.set='1' GROUP BY c.card_name, ab.Card_Name") or die; while ($row=mysql_fetch_array($sqlUncommon)) { $ucValues[]=$row['Aaverage']; } ///UNCOMMON VALUE IS VALUE * 3 $Uncommon = calculate_average($ucValues); $urm= ($Uncommon * 3) + $raremythic; ///GET THE COMMON VALUE $sqlCommon=mysql_query("SELECT AVG( ab.Price_Per ) AS Aaverage FROM auctions AS ab INNER JOIN cardlist AS c ON c.card_name = ab.Card_Name WHERE ab.Day >= '$queryday' AND c.rarity = 'Common' AND c.set='1' GROUP BY c.card_name, ab.Card_Name") or die; while ($row=mysql_fetch_array($sqlCommon)) { $cValues[]=$row['Aaverage']; } ///COMMON VALUE IS VALUE * 10 $common = calculate_average($cValues); //TOTAL SET 1 VALUE IS ALL VALUES ADDED UP $curm= ($common * 10) + $urm; ?> But I'm not real sure where the strain is coming from. The page seems to load really slow, and I'm not sure if I should just try and write all these queries as a separate function then have it write the data to a separate table, or if there is another way to optimize this code. I'm still have a lot to learn so I would appreciate any thoughts or ideas you folks can offer me. Many thanks 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>"; } ?> 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) { ?> 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()); } 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; } } ?> 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? 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 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 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!!! 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 |