PHP - Help Cleaning Up My Code A Little?
basically this is like 60% written by me with a few copy/paste. What I am looking to do, is clean up this code a little. Functionally it does what I want it to relatively well, but it does look very very messy and I would like it to be a little more tidy.
Any suggestions on how to do this? I am no PHP expert as you can most likely tell by the code itself. <?php require("cfg.php"); //FOLDER PATH $dir_cat= $imgpath; $openDir_cat = opendir($dir_cat); while (false !== ($fileNames_cat = readdir($openDir_cat))) { $check_cat = $dir_cat. "/" . $fileNames_cat; $size_cat = @getimagesize($check_cat); // this check mime of file if($fileNames == "." || $fileNames_cat == ".." || strpos($size_cat[mime], "image") === FALSE) { continue; // exclude everything wha is not image } else { $imagesAll_cat[] = $fileNames_cat; // create an array of images } } $imgnr_cat=0; $imgct_cat=count(glob($dir_cat . "*")); //COUNT THE NUMBER OF FILES IN THE UPLOAD DIR. echo '<center><fieldset class=fieldset>'; echo '<legend> IMGS '; echo ' (' .$imgct_cat. ' IMAGES)</legend><div>'; //GET IMAGES AND DISPLAY THEM while ($imgnr_cat<$imgct_cat){ echo '<a href=' .$dir_cat.$imagesAll_cat[$imgnr_cat]. '>'; echo '<img width=140 height=100 src=' .$dir_cat.$imagesAll_cat[$imgnr_cat]. '>'; echo '</a>'; $imgnr_cat++; } echo '</div></fieldset></center>'; ?> Similar TutorialsI need to pull a list of mp3 file names to create a playlist. I have a column for "priority" which will handle the rotation of the mp3's...so that a priority of 4 will play more often than a priority of 3...and so on. I have this code (which works) to select a column from the db that matches the selected criteria...AND has a priority of "4". If there are no matches, select a row that has a priority of "3". How can I clean up this code...preferably to remove the need for adding 2's after each variable? Also, is there a better way of handling this, so that it's ONE select...and then puts the mp3's in the playlist the correct number of times? Code: [Select] <?php $sql = "SELECT * FROM audio WHERE `client_id` = '$client' AND (`start_date` <= '$nownohour' AND `end_date` >= '$nownohour') AND `$dow` = '1' AND `is_active` = '1' AND (`start_hour` <= '$hournozero' AND `end_hour` >= '$hournozero') AND `priority` = '4' LIMIT 1"; $rs = mysql_query($sql,$dbc); $matches = 0; while ($row = mysql_fetch_assoc($rs)) { $matches++; echo "$row[title].mp3<br />"; } if (!$matches) { $sql2 = "SELECT * FROM audio WHERE `client_id` = '$client' AND (`start_date` <= '$now' AND `end_date` >= '$now') AND `$dow` = '1' AND `is_active` = '1' AND (`start_hour` <= '$hournozero' AND `end_hour` >= '$hournozero') AND `priority` = '3' LIMIT 1"; $rs2 = mysql_query($sql2,$dbc); $matches2 = 0; while ($row2 = mysql_fetch_assoc($rs2)) { $matches2++; echo "$row2[title].mp3<br />"; } } echo "-------------<br />"; ?> Thanks! I'm trying to clean up my code as best I know how and get rid of code that isn't necessary. This is where I'm most confused: On every page, I start a session and if someone goes to a page other than the index/login page, they are redirected if there is no session, otherwise, they are allowed to continue to view the page content. Here is my code: Code: [Select] <?php session_start(); $email=$_SESSION['email']; // is this line necessary on every page... if ($_SESSION['logged'] != 1) { $_SESSION['email'] = $email; // as well as this line? header("Location: index.php"); exit(); } ?> Basically, I need to know if the SESSION['email'] has to be set on every page, or does it stay set as long is the session is logged? If it stays set for the entire session, I shouldn't need to include the "$email=$_SESSION['email'];" line on every page, right? Also, if my thinking is correct, I shouldn't need to include the "$_SESSION['email'] = $email;" line unless I need to use the $email variable for some other purpose. Am I correct on this? Thanks for any input. Ok, i have this code that i want to print out the total number of times the defined username appears in my database with the defined date. Right now all it prints out is the echo at the end but with no numbers in the result. I just need help with getting it to display the number. Code: [Select] <?php //select a database to work with $selected = mysql_select_db("nwacompu_totals",$dbhandle) or die("Could not select examples"); $username = "bayyari"; $date = "3-16-2011"; $query = "SELECT COUNT(*) FROM totals WHERE date = '$date' AND username = '$username'"; $result = mysql_query($query) or die(mysql_error()); // Print out result while($row = mysql_fetch_array($result)){ echo "There are ". $row['COUNT(username)'] ." ". $row['date'] ." items."; echo "<br />"; echo $result; } ?> what is printed is this There are items. Resource id #2Resource id #3 which makes no sense to me. Any help is very much appreciated. Hi, This isn't so much a problem as my code/page works however my host shut down scripting on the site as too many connections to the database were left open apparently with this page. Also ive been looking into a way of cleaning up the code and making it less bloated but the only thing I have found is mysqli for running multiple queries in one go but I am unsure if this would help. Code: [Select] <?php session_start(); include("./includes/db_con.inc.php"); $image = $_GET["id"]; $id = str_replace("-", "/", $_GET["id"]); $cat = $_GET["cat"]; $sub_cat = $_GET["sub"]; $page_title = $cat . " - " . $sub_cat . " - " . $id; $sql_meta = mysql_query("SELECT * FROM english WHERE PRODID='$id' AND display='1'"); $row_meta = mysql_fetch_assoc($sql_meta); $meta_desc = $row_meta['META_DESC']; $meta_key = $row_meta['META_KEY']; include("./includes/head.php"); include("./includes/header.php"); ?> <div id="main-page-header"> <?php $header = "img/product-pages/product-specific-headers/" . $image . ".jpg"; if (file_exists($header)) { ?> <img src="<?php echo $img_loc; ?>/product-pages/product-specific-headers/<?php echo $image; ?>.jpg" width="940" height="310" /> <?php } else { $desc_sql = mysql_query("SELECT * FROM sub_cat WHERE name='$sub_cat'"); $row_desc = mysql_fetch_assoc($desc_sql); $description = $row_desc['description']; echo "<img src='$img_loc/product-pages/sub-cat-head/".str_replace(" ", "-", $row_desc['name'])."-sub-cat-head.jpg' width='940' height='310' />"; } ?> </div> <div id="page-content"> <div id="main-page-text"> <h1><?php $result = mysql_query("SELECT * FROM $table WHERE PRODID='$id' AND display='1'"); while($row = mysql_fetch_array($result)) { $prod_title = $row['PROD_TITLE']; echo $prod_title; ?> </h1> <h2 class="crumbs"><a href="<?php echo "$url/Products/$lang/"; ?>">Products</a> > <a href="<?php echo "$url/Category/$lang/".urlencode($cat)."/"; ?>"><?php echo $cat; ?></a> > <a href="<?php echo "$url/Range/$lang/".urlencode($cat)."/".urlencode($sub_cat)."/"; ?>"><?php echo $sub_cat; ?></a> > <?php echo $prod_title; ?> </h2> <p><?php echo $row['DESCRIPTION']; } ?></p> <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like layout="button_count" show_faces="false" width="170" font="verdana"></fb:like> <br /> <?php $i = 1; while ($i <= 8) { $filename = "img/product-pages/hovers-800px/" . $image . "-" . $i . ".jpg"; if (file_exists($filename)) { ?> <a class="fuglybox" rel="gxr" href="<?php echo "../../../../../" . $filename; ?>"> <img src="../../../../../img/product-pages/product-detail-90px/<?php echo $image . "-" . $i . ".jpg"; ?>" alt="" width="90" height="90" /></a> <?php } else { break; } $i++; } ?> <table> <th>Product Code</th> <th>Description</th> <?php $table_result = mysql_query("SELECT * FROM PRODID WHERE PRODID='$id'"); $table_entry = mysql_fetch_assoc($table_result); echo "<tr><td class='prod-id'>" . $table_entry['PROD_CODE'] . "</td>\n"; echo "<td class='prod-desc'>" . $table_entry['TA_DESC'] . "</td></tr>\n"; ?> </table> <div id="FAQ-wrap"><h2>Frequently Asked Questions</h2> <?php $QA_table = $lang . "_qanda"; if ($id=="") { $list_QA = mysql_query("SELECT * FROM $QA_table WHERE SUB_CATEGORY='$sub_cat' AND DISPLAY='1'"); } else { $list_QA = mysql_query("SELECT * FROM $QA_table WHERE PRODID='$id' AND DISPLAY='1'"); } while($row_QA = mysql_fetch_array($list_QA)) { echo "<div id='FAQ-QA'>"; echo "<h2 class='FAQ-question'>Q: ".$row_QA['QUESTION']."</h2>"; echo "<p class='FAQ-question'>A: ".$row_QA['ANSWER']."</p></div>"; } ?> <div id="FAQ-question"> <h2 class="white">Got a question about the <span class="got-question-product"><?php echo $sub_cat; ?></span> </h2> </div> </div> </div> <div id="totem-menu-container"><?php include("./includes/search.php") ?> <?php include("./includes/totem.php") ?> </div> </div> </div> <?php include("./footer.php") ?> Please note in the db_con.inc.php is the connection to the database stored in variable $con and included in the footer.php is mysql_close($con) which is also why I dont understand how connections are being left open, any help greatly appreciated. The attached script does everything I want it to do, but it's not very elegant. I could use some help cleaning it up. Any and all help is greatly appreciated. Thanks!!! Hi there I allow users to make new albums. For each album they give a full display name, eg "New Years Eve 2012 at Persons' place", and a shorter display eg "New Years Eve 2012". The first string should be stored in a db and should be shown exactly as it is, so for that string I have: Code: [Select] <?php //$fullname gets stored in the db $fullname = myql_real_escape_string(htmlentities($fullname)); //when pulled from the db, it is only echoed, nothing else: echo $fullname; ?> Now I presume it is safe so far. Now is the 'tricky' part. Currently this is what I do to the short name: Code: [Select] <?php //$shortname gets stored in the database $shortname = mysql_real_escape_string(urlncode(str_replace(' ','',strtolower($shortname)))); ?> Now from this shortname, before the mysql_real_escape_string(), it makes a directory with that name. Now what happens is, if there are special charcters like '@', the '@' changes into '%40'. So the directory would be eg 'fun%40myplace'. The directories get made without a problem, but for some reason my uploader won't upload to this directory. It isn't the uploaders fault because in folders without these special characters there is no problem with uploading. Any ideas on how to fix this, or what the best method is to clean a string for url/directory names? I have been trying to hack two parts of code together... I had code writen that will grab the text from a website and completely clean it of all junk except for full words... then echo it. Now I am trying to use the same script to pull from a database instead of a URL but am lost... Here is my code... I would make another donation to the site if we can get this going... THANK YOU! Code: [Select] <?php $con = mysql_connect("localhost","USERNAME","PASSWORD!"); mysql_select_db("DATABASE",$con); $get = "SELECT * FROM information_description WHERE information_id=4"; $SQ_query = mysql_query($get) or die("Query failed: $get\n" . mysql_error()); $fetch = mysql_fetch_array($SQ_query); $raw = $fetch['description']; /* Set internal character encoding to UTF-8 */ mb_internal_encoding("UTF-8"); mb_http_output( "UTF-8" ); ob_start("mb_output_handler"); function clean($html) { ###Remove number in html################ //$html = preg_replace("/[0-9]/", " ", $html); $html = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $html); // $html = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $html); echo $html; $html = str_replace(" ", " ", $html); $html = str_replace("&", " ", $html); $html = str_replace("-", " ", $html); ######remove space $html = preg_replace ('/<[^>]*>/', '', $html); $html = preg_replace('/\s\s+/', ', ', $html); $html = preg_replace('/[\s\W]+/',' ',$html); // Strip off spaces and non-alpha-numeric return $html; } #call function //$raw = StripHtmlTags($raw); $raw = clean($raw); echo $raw; ##echo clean($html); $url = (isset($_GET['url']) ?$_GET['url'] : 0); $str = file_get_contents($url); ####################################################################3 function get_url_contents($url){ $crl = curl_init(); $timeout = 5; curl_setopt ($crl, CURLOPT_URL,$url); curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout); $ret = curl_exec($crl); curl_close($crl); return $ret; } #--------------------------------------Strip html tag---------------------------------------------------- function StripHtmlTags( $text ) { // PHP's strip_tags() function will remove tags, but it // doesn't remove scripts, styles, and other unwanted // invisible text between tags. Also, as a prelude to // tokenizing the text, we need to insure that when // block-level tags (such as <p> or <div>) are removed, // neighboring words aren't joined. $text = preg_replace( array( // Remove invisible content '@<head[^>]*?>.*?</head>@siu', '@<style[^>]*?>.*?</style>@siu', '@<script[^>]*?.*?</script>@siu', '@<object[^>]*?.*?</object>@siu', '@<embed[^>]*?.*?</embed>@siu', '@<applet[^>]*?.*?</applet>@siu', '@<noframes[^>]*?.*?</noframes>@siu', '@<noscript[^>]*?.*?</noscript>@siu', '@<noembed[^>]*?.*?</noembed>@siu', // Add line breaks before & after blocks '@<((br)|(hr))@iu', '@</?((address)|(blockquote)|(center)|(del))@iu', '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu', '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu', '@</?((table)|(th)|(td)|(caption))@iu', '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu', '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu', '@</?((frameset)|(frame)|(iframe))@iu', ), array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0",),$text ); // Remove all remaining tags and comments and return. return strtolower( $text ); } function RemoveComments( & $string ) { $string = preg_replace("%(#|;|(//)).*%","",$string); $string = preg_replace("%/\*(?:(?!\*/).)*\*/%s","",$string); // google for negative lookahead return $string; } $html = StripHtmlTags($str); ###Remove number in html################ $html = preg_replace("/[0-9]/", " ", $html); #replace by ' ' $html = str_replace(" ", " ", $html); ######remove any words################ $remove_word = file("swords.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); foreach($remove_word as $word) { $html = preg_replace("/\b". $word ."\b/", " ", $html); } ######remove space $html = preg_replace ('/<[^>]*>/', '', $html); $html = preg_replace('/\b\s+/', ', ', $html); $html = preg_replace('/[\b\W]+/',', ',$html); // Strip off spaces and non-alpha-numeric #remove white space, Keep : . ( ) : & //$html = preg_replace('/\s+/', ', ', $html); ###process######################################################################### $array_loop = explode(",", $html); $array_loop1 = $array_loop; $arr_tem = array(); foreach($array_loop as $key=>$val) { if(in_array($val, $array_loop1)) { if(!$arr_tem[$val]) $arr_tem[$val] = 0; $arr_tem[$val] += 1; if ( ($k = array_search($val, $array_loop1) ) !== false ) unset($array_loop1[$k]); } } arsort($arr_tem); ###echo top 20 words############################################################ echo "<h3>Top 20 words used most</h3>"; $i = 1; foreach($arr_tem as $key=>$val) { if($i<=20) { echo $i.": ".$key." (".$val." words)<br />"; $i++; }else break; } echo "<hr />"; ###print array##################################################################### echo (implode(", ", array_keys($arr_tem))); ?> I am cleaning up my website (replace tables with divs and turning all design code in to CSS). I would like to know a couple things. First, I see that register_globals is deprecated, but I still see new blog posts and such saying to keep it. I want to know if I should remove it, how it works, and if I do remove it what should I replace it with. Also, I have code like: Code: [Select] '".$SETTINGS['siteurl']."uploaded/".$val["pict_url"]."' and I was wondering whether it can be replaced with Javascript. Please don't call me a noob or tell me to Google it because when it comes to me, Google, and PHP; I'm like a kid in a candy shop and all the candy is filled with dirt. Hi. I've been banging my head against the wall with this stupid problem and I just figured out the problem.
I scrape data from a website. I query my table to see if I already have everything in there. If no match is found, I insert it.
Today, I noticed even after inserting, my script kept telling me there's a new entry I need to insert, despite it actually being there when I physically check the table.
But when I echo the query out and run it in phpmyadmin, it finds the row. But not if I run the query directly in my script.
Turns out, there are several invisible characters in my string. When I do var_dump(), it says length is 25. When I copy and paste the string into notepad, then back into a fresh php script and wrap it in quotes and echo out a strlen(), I get 21. There are apparently 4 invisible characters that I can't see. I trim() everything, so that apparently didn't catch it.
So... is there a good way to "clean" my data before inserting or comparing it to avoid this in the future? This wasted a ton of time and I hope to find a way to clean this junk out of my data.
Thanks! It just seems like I run into this sort of thing often when it's data scraped from the web. (breaks my regex! grr!)
Just want to finalize what the best options/functions are when cleaning user supplied input in the following 3 situations: 1. Inserting data into a database 2. Sending data to an email (and displaying it as HTML) 3. Displaying data back to screen This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=326004.0 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>"; } ?> 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) { ?> 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; } } ?> 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? 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 |