PHP - Problems With This Code
can someone please tell me what is wrong with this code?
<?php function documentType(){ echo <<<HEREDOC <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ` ` "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> } HEREDOC; ?> Similar Tutorialsclass curl2{ private $curl_init; private $CURLOPT_URL; public function connect(){ $this->curl_init = curl_init(); } public function debug(){ curl_setopt($this->curl_init, CURLOPT_VERBOSE, TRUE); $fp = fopen("curl2.txt", "w"); curl_setopt($this->curl_init, CURLOPT_STDERR, $fp); curl_setopt($this->curl_init, CURLOPT_RETURNTRANSFER, TRUE); } public function setUrl($url = null){ $this->CURLOPT_URL = $url; curl_setopt($this->curl_init, CURLOPT_URL, $this->CURLOPT_URL); } public function execute(){ $out = curl_exec($this->curl_init); curl_close($this->curl_init); return $out; } } $curl2 = new curl2; $curl2->connect(); $curl2->setUrl("http://www.linuxformat.co.uk"); $curl2->debug(); echo $curl2->execute(); It display a blank page like attachment result1.jpg, but if I move the $fp = fopen("curl2.txt", "w"); curl_setopt($this->curl_init, CURLOPT_STDERR, $fp); curl_setopt($this->curl_init, CURLOPT_RETURNTRANSFER, TRUE); from function debug() and join it with function execute() like this: public function execute(){ $fp = fopen("curl2.txt", "w"); curl_setopt($this->curl_init, CURLOPT_STDERR, $fp); curl_setopt($this->curl_init, CURLOPT_RETURNTRANSFER, TRUE); $out = curl_exec($this->curl_init); curl_close($this->curl_init); return $out; } it return me Linuxformat content ( expected result ) like result2.jpg below is the working code : class curl2{ private $curl_init; private $CURLOPT_URL; public function connect(){ $this->curl_init = curl_init(); } public function debug(){ curl_setopt($this->curl_init, CURLOPT_VERBOSE, TRUE); } public function setUrl($url = null){ $this->CURLOPT_URL = $url; curl_setopt($this->curl_init, CURLOPT_URL, $this->CURLOPT_URL); } public function execute(){ $fp = fopen("curl2.txt", "w"); curl_setopt($this->curl_init, CURLOPT_STDERR, $fp); curl_setopt($this->curl_init, CURLOPT_RETURNTRANSFER, TRUE); $out = curl_exec($this->curl_init); curl_close($this->curl_init); return $out; } } $curl2 = new curl2; $curl2->connect(); $curl2->setUrl("http://www.linuxformat.co.uk"); $curl2->debug(); echo $curl2->execute(); Why I couldn't split "CURLOPT_STDERR, CURLOPT_RETURNTRANSFER" with "curl_exec" Hey, I got this script off phpfreaks in the post "Basic Pagination Code", and got it to work except I'm experiencing this really tiny problem. The script displays only the first row in my table, and displays 127 times, which is how many rows I have total in the table. This is where I have this script running at. You can go there to see what I'm talking about: http://www.djsmiley.net/guestbook.php This is the code I got and tweaked: Code: [Select] <?php //your username $username = "your username"; //your password $password = "your password"; //your mySQL server $host = "your hostname"; //The name of the database your table is in $database = "your database"; //connect, but if there is a problem, display an error message telling why there is a problem $conn = mysql_connect($host,$username,$password) or die("Error connecting to Database!<br>" . mysql_error()); //Choose the database from your mySQL server, but if there is a problem, display an error telling why $db = mysql_select_db($database) or die("Cannot select database!<br>" . mysql_error()); // find out how many rows are in the table $sql = "SELECT COUNT(*) FROM comments"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); $r = mysql_fetch_row($result); $numrows = $r[0]; // number of rows to show per page $rowsperpage = 10; // find out total pages $totalpages = ceil($numrows / $rowsperpage); // get the current page or set a default if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) { // cast var as int $currentpage = (int) $_GET['currentpage']; } else { // default page num $currentpage = 1; } // end if // if current page is greater than total pages... if ($currentpage > $totalpages) { // set current page to last page $currentpage = $totalpages; } // end if // if current page is less than first page... if ($currentpage < 1) { // set current page to first page $currentpage = 1; } // end if // the offset of the list, based on current page $offset = ($currentpage - 1) * $rowsperpage; // get the info from the db $sql = "SELECT * FROM comments ORDER BY commentid DESC LIMIT $offset, $rowsperpage"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); // while there are rows to be fetched... while ($list = mysql_fetch_assoc($result)) { // echo data if ($name == 'DJ Smiley' && $adminkey == 'adminkey') { echo(" <div style=\"border-radius: 10px; border: solid 2px #E5E5E5; padding: 10px; width: 95%; background: #F6F6F6;\"> <p> <a name=\"$commentid\" id=\"$commentid\"></a><img src=\"http://www.djsmiley.net/images/Icons/Arrows/Right 2.png\" class=\"fltlft2\" height=\"25\" width=\"25\"><strong>$name</strong> (<a href=\"http://whois.domaintools.com/$ip\"><font size=1>$ip</font></a>) says: <br><p class=\"BottomBorder\"></p> <table><tr><td><img src=\"http://www.djsmiley.net/images/Self/Self (2).jpg\" height=\"50\" width=\"50\"></td><td>$comment</td></tr></table> <br><p class=\"BottomBorder\"></p> added on $time<p><em>$email</em></p> </p> </div><br> "); } elseif ($name == false) { echo(" <div style=\"border-radius: 10px; border: solid 2px #E5E5E5; padding: 10px; width: 95%; background: #F6F6F6;\"> <p> <a name=\"$commentid\" id=\"$commentid\"></a><img src=\"http://www.djsmiley.net/images/Icons/Arrows/Right 2.png\" class=\"fltlft2\" height=\"25\" width=\"25\"><strong>Anonymous</strong> (<a href=\"http://whois.domaintools.com/$ip\"><font size=1>$ip</font></a>) says: <br><p class=\"BottomBorder\"></p> <table><tr><td><img src=\"http://www.djsmiley.net/images/Icons/People/Anonymous 2.png\" height=\"50\" width=\"50\"></td><td>$comment</td></tr></table> <br><p class=\"BottomBorder\"></p>added on $time<p><em>$email</em></p> </p> </div><br> "); } else { echo(" <div style=\"border-radius: 10px; border: solid 2px #E5E5E5; padding: 10px; width: 95%; background: #F6F6F6;\"> <p> <a name=\"$commentid\" id=\"$commentid\"></a><img src=\"http://www.djsmiley.net/images/Icons/Arrows/Right 2.png\" class=\"fltlft2\" height=\"25\" width=\"25\"><strong>$name</strong> (<a href=\"http://whois.domaintools.com/$ip\"><font size=1>$ip</font></a>) says: <br><p class=\"BottomBorder\"></p> <table><tr><td><img src=\"http://www.djsmiley.net/images/Icons/People/Anonymous 2.png\" height=\"50\" width=\"50\"></td><td>$comment</td></tr></table> <br><p class=\"BottomBorder\"></p> added on $time<p><em>$email</em></p> </p> </div><br> "); } } // end while /****** build the pagination links ******/ // range of num links to show $range = 3; // if not on page 1, don't show back links if ($currentpage > 1) { // show << link to go back to page 1 echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> "; // get previous page num $prevpage = $currentpage - 1; // show < link to go back to 1 page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> "; } // end if // loop to show links to range of pages around current page for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalpages)) { // if we're on current page... if ($x == $currentpage) { // 'highlight' it but don't make a link echo " [<b>$x</b>] "; // if not current page... } else { // make it a link echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> "; } // end else } // end if } // end for // if not on last page, show forward and last page links if ($currentpage != $totalpages) { // get next page $nextpage = $currentpage + 1; // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> "; // echo forward link for lastpage echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> "; } // end if /****** end build pagination links ******/ ?> I was wondering if someone can tell me what I have done wrong with this code: <?php foreach ($row['received'] as $data) { $data += $received; } echo $received; ?> It should be adding the number 2 three times, so it should be echoing 6 but its not. Problem 1 I have is that nothing is being added to the variable $received, and problem 2 is that I suspect $received will not become 6, but rather 222. Am I correct? I have a form on a page which is accessed when a user logs into their account. The form dynamically pulls bits of the users info from 2 tables in a mysql database, Tables (ITEMS) and Table (USERS). Table (USERS) holds the users info (NAME, EMAIL ETC) while Table (ITEMS) hold information about the users items for which they may have several of. When the form page is accessed all the users items from Table (ITEMS) are dynamically shown on the form with several radio buttons at the side of each item. The user can tick certain radio buttonss at the side of each item and click the send button. TRYING TO ACHIEVE... After the form is sent a thank you message is returned on the same page with details of the items and what radios were ticked. An Email of the same is sent to user with info of the items and what radios were ticked. An Email is also sent to me with same info of the items and what radios were ticked. WHAT I AM ACHIEVING SO FAR WITH CODE BELOW: The form page is ok showing all users items, radios, send button etc. The returned thank you page is fine showing items, what radios were checked etc. Even the email part is working sending an email to the user and myself. THE PROBLEM IS THAT A SEPERATE EMAIL IS SENT TO BOTH OF US FOR EACH ITEM THE USER HAS IN THE DATABASE. I JUST WANT ONE EMAIL SENDING TO BOTH OF US DETAILING ALL ITEMS. I realise this is because of the while statement in the call to the database which is looping the below code for each item thus sending an email for each item. What I can not suss out is how to send just the one email with all items on. Tried moving the closing loop bracket all over the place and parts of the code but to not avail. THE CODE: (some unecessary code removed from echo/thank you to simplify) <table width="100%"> <tr> <td class="bodytext"><strong>Name</strong></td> <td class="bodytext"><strong>Ref</strong></td> <td><strong>Status</strong></td> <td><strong>Type</strong></td> <td><strong>Date</strong></td> <td><strong>Extend</strong></td> <td><strong>Feature</strong></td> <td><strong>Offer</strong></td> </tr> <form action="example-this-page" method="post"> <input type="hidden" name="action" value="0"> <input type="hidden" name="id" value="<?php echo $_REQUEST["id"]; ?>"> <?php $sql = "SELECT * FROM ".$TABLES["items"]." WHERE user_id='".$_SESSION["UserAccount"]."'"; $sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql); while ($ITEMS = mysql_fetch_assoc($sql_result)) { $sql = "SELECT * FROM ".$TABLES["users"]." WHERE id='".$ITEMS["user_id"]."'"; $sql_resultT = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql); $USER=mysql_fetch_assoc($sql_resultT); ?> <? if (isset($action)) { $to = $USER["email"]; $mailheader = "From: $email\r\n"; $mailheader .= "Reply-To: $email\r\n"; $mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; $msg = "Dear ".stripslashes($USER["name"])."<br><br> <table><tr> <td><strong>Name</strong></td> <td><strong>Ref No</strong></td> <td><strong>Status</strong></td> <td><strong>Type</strong></td> <td><strong>Date</strong></td> <td><strong>Extend</strong></td> <td><strong>Feature</strong></td> <td><strong>Offer</strong></td> </tr> <tr> <td>".stripslashes($ITEMS["name"])."</td> <td>".stripslashes($ITEMS["ref"])."</td> <td>".stripslashes($ITEMS["status"])."</td> <td>".stripslashes($ITEMS["type"])."</td> <td>".stripslashes($ITEMS["date"])."</td> <td>".$_POST['extend']."</td> <td>".$_POST['feature']."</td> <td>".$_POST['offer']."</td> </tr> </table> "; mail($to, "subject", $msg, $mailheader) or die ("Failure"); mail("me@me.co.uk", "subject", $msg, $mailheader) or die ("Failure"); echo "<br /><br /><font size=2> <strong><center>Thank you!</center><br /> Your details of your request has been sent:</center><br /> "; }; ?> <tr> <td><?php echo stripslashes($ITEMS["name"]); ?></td> <td><?php echo stripslashes($ITEMS["ref"]); ?></td> <td><?php echo stripslashes($ITEMS["status"]); ?></td> <td><?php echo stripslashes($ITEMS["type"]); ?></td> <td><?php echo stripslashes($ITEMS["date"]); ?></td> <td><input type="radio" name="extend<?php echo stripslashes($ITEMS["id"]); ?>" value="No"> No <input type="radio" name="extend<?php echo stripslashes($ITEMS["id"]); ?>" value="Yes" /> Yes</td> <td><input type="radio" name="featured<?php echo stripslashes($ITEMS["id"]); ?>" value="No"> No <input type="radio" name="featured<?php echo stripslashes($ITEMS["id"]); ?>" value="Yes" /> Yes</td> <td><input type="radio" name="latedeal<?php echo stripslashes($ITEMS["id"]); ?>" value="No"> No <input type="radio" name="latedeal<?php echo stripslashes($ITEMS["id"]); ?>" value="Yes" /> Yes</td> </tr> <?php } ?> <tr> <td> <input type="submit" name="Submit" value="Send"></td> </tr></table> </form> </table> 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. 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) { ?> 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 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 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? 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 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!!! 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 />
|