PHP - Must Be An Easier/more Efficient Way To Code This
Hello, I'm new to PHP and I have come up with the following code for my navigation but I am sure there has to be an easier and more efficient way to do this. Someone please start me on the right path. Thanks
Code: [Select] <?php //Get selected page/sub page if (isset($_GET['page'])) { $sel_page = $_GET['page']; $sel_sub_page = ''; } elseif (isset($_GET['sub_page'])) { $sel_page = ''; $sel_sub_page = $_GET['sub_page']; } else { $sel_page = ''; $sel_sub_page = ''; } ?> Code: [Select] <!--Begin Navigation--> <ul> <?php //run the loop to get the page titles $query = "SELECT * FROM pages ORDER BY position ASC"; $page_set = mysql_query($query); confirm_query($page_set); while($page = mysql_fetch_array($page_set)){ echo '<li><a href="content.php?page=' . urlencode($page['id']) . '">' . $page['page_name'] . '</a></li>'; //run sub page query to see if the ul tag is needed $query = "SELECT * FROM sub_pages WHERE page_id = {$page['id']} ORDER BY position ASC"; $sub_page_set = mysql_query($query); confirm_query($sub_page_set); $sub_page = mysql_fetch_array($sub_page_set); if ($sub_page !=''){ echo '<ul>'; } //run the sub page loop again to display the sub page title $query = "SELECT * FROM sub_pages WHERE page_id = {$page['id']} ORDER BY position ASC"; $sub_page_set = mysql_query($query); confirm_query($sub_page_set); while($sub_page = mysql_fetch_array($sub_page_set)) { echo '<li><a href="content.php?sub_page=' . urlencode($sub_page['id']) . '">' . $sub_page['page_name'] . '</a></li>'; } //run the sub page loop for the last time to see if the end ul tag is needed $query = "SELECT * FROM sub_pages WHERE page_id = {$page['id']} ORDER BY position ASC"; $sub_page_set = mysql_query($query); confirm_query($sub_page_set); $sub_page = mysql_fetch_array($sub_page_set); if ($sub_page !='') { echo '</ul>'; } } ?> </ul> <!--End Navigation--> Similar TutorialsHI, My code works but I was wondering if there's a simpler/cleaner way to code it ... Code: [Select] <?php require_once('config.php'); // code to get data form database mysql_select_db($database, $makeconnection); $sql_get_categories = " SELECT * FROM tbl_categories ORDER BY category_id ASC"; $get_categories = mysql_query($sql_get_categories, $makeconnection) or die(mysql_error()); $row_get_categories = mysql_fetch_assoc($get_categories); $totalRows_get_categories = mysql_num_rows($get_categories); // i named the 3 fields form the form in the HTML so i can update them into the tadabase $category_1 = $_POST['category_1']; $category_2 = $_POST['category_2']; $category_3 = $_POST['category_3']; //updating the databse if (isset($_POST['submitted_categories'])&&($_POST['submitted_categories'] == "yes")) { $register_query = "SELECT category_id FROM tbl_categories WHERE category_id='$category_id'"; mysql_select_db($database, $makeconnection); $sql_modify1 = ("UPDATE `tbl_categories` SET `category_name` = '$category_1' WHERE `category_id` =1"); $sql_modify2 = ("UPDATE `tbl_categories` SET `category_name` = '$category_2' WHERE `category_id` =2"); $sql_modify3 = ("UPDATE `tbl_categories` SET `category_name` = '$category_3' WHERE `category_id` =3"); $Result1 = mysql_query($sql_modify1, $makeconnection) or die(mysql_error()); $Result2 = mysql_query($sql_modify2, $makeconnection) or die(mysql_error()); $Result3 = mysql_query($sql_modify3, $makeconnection) or die(mysql_error()); header ("Location: the-rest.php"); } ?> here's the form in the html part Code: [Select] <!--CATEGORIES --> <h2>Categories</h2> <form action="" method="post" enctype="multipart/form-data" name="category-form" id="category-form"> <?php do { ?> <h3><input class="user-form-input" id="category_<?php echo $row_get_categories['category_id'];?>" name="category_<?php echo $row_get_categories['category_id'];?>" type="text" value="<?php echo $row_get_categories['category_name'];?>" /></h3> <?php } while ($row_get_categories = mysql_fetch_assoc($get_categories)); ?> <input name="submitted_categories" type="hidden" id="submitted_categories" value="yes" /> <input name="submit" type="submit" class="button-save" id="submit" value="update categories"/> </form> <!--END OF CATEGORIES--> <?php $result = "SELECT * FROM portfolio"; $result = mysql_query ($result) or die (mysql_error()); $i=0; while($row = mysql_fetch_assoc($result)) { if($i==0) echo '<div class="portfolioPage">'; if($i==2) $divclass = 'portfolioProjectWrapper borderWhite'; else $divclass = 'portfolioProjectWrapper borderGray'; echo ' <div class="'.$divclass.'"> <a href="portfolioPage.html" class="image asyncImgLoad" title="img/'.$row['image290x290'].'"></a> <p class="imageDesc">'.$row['image290x290_phot'].'</p> <h3 class="title">'.$row['title'].'</h3> <p class="subtitle">'.$row['subtitle'].'</p> <p class="desc"> '.substr($row['description'], 0, 1200).' <a href="portfolioPage.html" class="commonLink">Read more</a> </p> </div> '; if($i==2) echo '</div>'; if(i==2) $i=0; else $i++; } ?> Please help me im backward at this been along time. This question includes MySQL, but I have a feeling the answer will involve PHP so putting it here for now. If it should be moved, feel free Say I have a for loop that iterates through a certain amount of times and updates a value in my database EACH ITERATION thru the loop. In other words, we're connecting to the database multiple times. Seems very inefficient, so I'd like to see if there is a better way. Here is a basic example of the "bad" way (FYI, this code is basically reordering items after one of them moves down in the list)... Code: [Select] for ($a=$oldvalue+1; $a<=$othervalue; $a++) { $sql = "UPDATE tablewithids SET id=id - 1 WHERE id=$a"; $result = mysql_query($sql, $connection); if (!$result) { die("Database query failed: " . mysql_error()); } else { } So if $othervalue happened to be 80, then it would be 80 separate connections to the database! I imagine it would make a lot more sense to gather the data first (into an array I presume) and then make one connection to the database an update that way, but I'm having trouble wrapping my head around how to do it based on this type of example. Can anyone offer suggestions to help make this type of for loop code more efficient? $text=$_POST['Txt']; $strrep1=str_replace('z', 'a', $text); $strrep2=str_replace('y', 'z', $strrep1); This code is a little bit time consuming to do I'm trying to make all the letters one higher, For example "Foo bar" becomes "Gpp Cbs" The reason I'm trying to do this is a long story, But anyway is there an easier way to do it reather than the way I was doing it? And would it work? Here is my long drawn out code. Is there a better way of doing this and how can I echo the JS without it messing up the php. I really need the JS link to work! <?php if(isset($_SESSION['rest'])){ echo'<table width="300" border="0" cellpadding="0" cellspacing="0"> <tr> <td valign="middle" class="topnav"><div align="center" ><a href="index.php">Home</a></div></td> <td valign="middle" class="topnav"><div align="center"><a href="restpanel.php">User Panel</a></div></td> <td valign="middle" class="topnav"><div align="center"><a href="logout.php">Logout</a></div></td> </tr> </table>';} if(isset($_SESSION['chef'])){ echo' <table width="300" border="0" cellpadding="0" cellspacing="0"> <tr> <td valign="middle" class="topnav"><div align="center" ><a href="index.php">Home</a></div></td> <td valign="middle" class="topnav"><div align="center"><a href="chefpanel.php">User Panel</a></div></td> <td valign="middle" class="topnav"><div align="center"><a href="logout.php">Logout</a></div></td> </tr> </table>';} if(!isset($_SESSION['chef']) || !isset($_SESSION['rest'])){ echo "<table width='350' border='0' cellpadding='0' cellspacing='0'> <tr> <td valign='middle' class='topnav'><div align='center'><a href='index.php'>Home</a></div></td> <td valign='middle' class='topnav'><div align='center' >"<a href="javascript:void(0)" onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">Log In</a></div></td> <td valign="middle"class="topnav"><div align="center"><a href="register.php">Sign Up</a></div></td> <td valign="middle"class="topnav"><div align="center" ><a href="contact.php">Contact Us</a></div></td> </tr> </table>";} ?> Currently what I have is this:
$url="http://www.nfl.com/liveupdate/scorestrip/postseason/ss.xml"; $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); // get the url contents $data = curl_exec($ch); // execute curl request curl_close($ch); $xml = simplexml_load_string($data); foreach($xml->gms->g as $games) { if(!empty($games['vtn'])) { if ((($games['gt']) =='WC') && (($games['q'])== 'F')) { echo "<li data-subcategory='Final Scores' data-category='Wild Card Games' data-color='1979ab'><a href='#'>",$games['htn']," ",$games['hs']," ",$games['vtn']," ",$games['vs']," Final</a></li>"; } if (($games['gt']) =='DIV') { echo "<li data-subcategory='Final Scores' data-category='Divisional Games' data-color='14ab05'><a href='#'>",$games['htn']," ",$games['hs']," ",$games['vtn']," ",$games['vs']," ",$games['d']," at ",$games['t'], "</a></li>"; } if (($games['gt']) == 'CON') { echo "<li data-subcategory='Conference Games' data-category='Sunday' data-color='000000'><a href='#'>",$games['htn']," ",$games['hs']," ",$games['vtn']," ",$games['vs']," ",$games['d']," at ",$games['t'], "</a></li>"; } } }It works great, Thanks to some help! The only thing I'd like to do now is have the output be a little more inline ...currently it reads the xml line by line and outputs the each item.. the order is the problem... It does this: Wild Card game Wild Card game Div game Div game Conference game Conference game Div game Div game Wild Card game Wild Card game I'd like it to output one type at a time....basically grouping all types together.. WC game Div game Conference game I continue to learn but this one is stumping me... I did get an idea from someone but not sure how to carry this one out... Instead of outputting it directly you could just add it to an array in the first loop So for each game you do $games[$type][] = $game; Then you can add another loop (for output) where you will have them sorted Just not sure how to handle that.. I'm feeling a bit lost at the moment... Is this in reference to putting $games[$type] = $game in place of foreach($xml->gms->g as $games)? I guess the second part has me lost as well adding another loop for output... needing to be sorted because each output is styled differently I guess I'm just not understanding.... can anyone clarify for me please? Thanks everyone! Whenever people are going to update something, they have a list of things to update. Whenever they choose the file they wish to edit/re-upload, they click the [EDIT] link beside it. This takes them to the update page, of course on the same file. They still have edit.php?id=3 in the URL, for example. But whenever they click Submit, how am I suppose to get the ID again? Is there a less junky way to do it then this: if(!$_GET['id'] && $_POST['id']) { $id = $_POST['id']; } elseif($_GET['id'] && !$_POST['id']) { $id = $_GET['id']; } else { } I have about 350 rows that I have to update a single column in each row. I coded so I can do each row individually but I was wondering if there is a way to update all of them at once. Hence saving me time. This is my code: Code: [Select] <?PHP include "dbmembers.php"; ?> <?php if(isset($submit)){ $ID = mysql_real_escape_string(trim($_POST['ID'])); $result = mysql_query("SELECT response FROM myuser WHERE ID ='$ID'"); $row = mysql_fetch_array($result); $res = hash("sha256", $row['response'] .$salt ); { echo $row['response'] ."----".$res; echo "<br /><br />"; } } mysql_query("UPDATE myuser SET response='$res' WHERE ID = '$ID'"); printf ("Updated records: %d\n", mysql_affected_rows()); ?> Thanks in advance for any advise. Hi , I'm new on this forum so don't judge too hard.. But I have a few questions. I am recently new to PHP as this is my first computer language I've learnt besides HTML. My first question is, what's the difference between !== and !=, and is it more secure to use !== when comparing two fields such as passwords? I've different things and this has confused me.. And my second question is, I have this piece of code Code: [Select] /* option error checking */ $field = "option"; // Use field name for option /* Check if the option picked is from the list of options to choose from*/ if($suboption !== "option1" || $suboption !== "option2" || $suboption !== "option3" || $suboption !== "option4" || $suboption !== "option5" || $suboption !== "option6" || $suboption !== "option7"){ $form->setError($field, "* Unexpected error with option"); } I'm guessing in the long run, this will slow down my script.. is there an easier way of checking without using || $suboption !== and is it okay if I've used !==? Like I said I'm new to this so please don't flame.. I've done some research but I can't seem to find some accurate answer. Thank you, ZT Code: [Select] <?php $IPaddress = $_SERVER['REMOTE_ADDR']; if(stristr($IPaddress, "123.456.58.451") || stristr($IPaddress, "123.126.456.10") || stristr($IPaddress, "123.126.456.10")) { echo "<center><b><i>CWB permits you to views this page...</i></b></center></br>"; echo '<center><b><font size="5">'.$IPaddress.'</font></b></center>'; } else { echo "<center><b>CWB DOES NOT PERMIT YOU TO VIEW THIS PAGE</b></center>"; } exit; ?> how do I make it to where I dont have to keep adding on to Code: [Select] if(stristr($IPaddress, "123.456.58.451") || stristr($IPaddress, "123.126.456.10") || stristr($IPaddress, "123.126.456.10")) this xml_parse_into_struct($iP=xml_parser_create(), curl_exec($ch), $bR, $bJ);xml_parser_free($iP); echo "::: ".strip_tags(str_replace("<br>","\n",$bR[$bJ['MESSAGE'][0]]['value']))."\n"; or... $xml = simplexml_load_string(curl_exec($ch)); foreach($xml->xml as $message){ echo strip_tags($message->message)."\n";} Just want to know which of these two would execute faster and if there was a better way that would be faster than both of these options? Thanks I have some code which i think is really inefficient especially as there will be more more conditions to be met. I was thinking about using s switch but don't know if this is possible or if it's best leaving as it is. Any ideas? if($parts[($i-1)]=="forum") { //do some code } else if($parts[($i-2)]=="forum") { //do code } else if (($parts[($i-1)]=="list-messages") && (isset($parts[($i+1)]))) { //do code } else { // do some code } $ch = curl_init(); //////////////////////////////////// //////////////////////////////////// for($cwb=1; $cwb!=$Amount; $cwb++) { $action = file_get_contents($Game."refresh_stat_manual?user_id=".$Keys[0]."&auth_key=".$Keys[1]); $xml = simplexml_load_string($action); foreach($xml->xml->viewer->user as $stats) { $energy=$stats->energy; $level=$stats->level; } if($energy <= 0 || $Stop <= $level) { echo "REACHED EITHER LEVEL $Stop OR... YOU ARE OUT OF ENERGY...\n"; sleep(100000); } $send1 = $Game."send_requests?user_id=".$IDone."&to_user_ids=".$Keys[0]."&auth_key=".$AuthOne; curl_setopt($ch, CURLOPT_URL, $send1); curl_exec($ch); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $send2 = $Game."send_requests?user_id=".$IDtwo."&to_user_ids=".$Keys[0]."&auth_key=".$AuthTwo; curl_setopt($ch, CURLOPT_URL, $send2); curl_exec($ch); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $accept = $Game."accept_all_mob_requests?user_id=".$Keys[0]."&auth_key=".$Keys[1]; curl_setopt($ch, CURLOPT_URL, $accept); curl_exec($ch); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $job = $Game."do_job?user_id=".$Keys[0]."&job_id=7200018&auth_key=".$Keys[1]; curl_setopt($ch, CURLOPT_URL, $job); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $exec1 = curl_exec($ch); if(stristr($exec1, 'You gained 6') || stristr($exec1, 'You gained 1') || stristr($exec1, 'ambulance')) { echo "#$cwb: <-- You've gained 1 ambulance... Level - ".$level." ::: ENERGY - ".$energy." :::\n"; } for($abc =1; $abc!=2; $abc++){ $remove1 = $Game."remove_mob_member?user_id=".$Keys[0]."&remove_user_id=".$IDone."&auth_key=".$Keys[1]; curl_setopt($ch, CURLOPT_URL, $remove1); curl_exec($ch); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);} for($abc =1; $abc!=2; $abc++){ $remove2 = $Game."remove_mob_member?user_id=".$Keys[0]."&remove_user_id=".$IDtwo."&auth_key=".$Keys[1]; curl_setopt($ch, CURLOPT_URL, $remove2); curl_exec($ch); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);} $sell = $Game."buy_item?user_id=".$Keys[0]."&item_id=32&amount=".$Amount."&auth_key=".$Keys[1]; curl_setopt($ch, CURLOPT_URL, $sell); $exec2 = curl_exec($ch); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if(stristr($exec2, 'sold')) { echo "::: You've sold 1 ambulance...\n"; } } curl_close(); Any idea on how I could make this faster or what I could change to make it to more efficient Hi all! I'm a real noob and this is my first time making a website and I haven't hosted it yet. I'm trying to make a website that is fast and secure. My pages look something like this. Code: [Select] <?php include("header.php");include("sidebar.php"); ?> HTML CODES <?php include("footer.php"); ?> 1. Are these php files cached after their first load? When I go to another page, those parts seem to stay still. 2. Is this code secure? And now I'm starting to make product pages which will be around 40 pages. So I'm considering something like this... Code: [Select] <?php include("header.php");include("sidebar.php"); ?> <a href="index.php?page=a">Page A</a> <?php $page = $_GET['page']; if (file_exists('pages/'.$page.'.php')) { include('pages/'.$page.'.php'); } ?> <?php include("footer.php"); ?> 3. Is it better to make every page like this since it will load header, sidebar, footer only once? 4. How should I protect from the user input data, by making an array of allowed files or by prohibiting "." and "/" ? Thank you in advance. Hi guys, I want to find the most efficient way of setting a php variable through a link.
What I'm trying to achieve is to allow the user to select a category and their location and store the two variables to update my database results. I first used the GET method, but since the page refreshes when the user selects any other Get variable, so it ends up reseting the variables. Currently I have the category and locations as drop down menu with links to each of the options. I'll appreciate any help. Thank you. :]
Hi guys, I'm developing a website which allows people to connect and follow each other's activity (like Twitter, for example). To simplify everything, let's say I only have 2 tables: 1. Followers id | follower_id | id_to_follow ------------------------------------ 2. Activity id | member_id | message | time ----------------------------------------- Let's say John is following Jane and Bob. I want to create a "news" page and display the last 20 messages from Bob and Jane, chronologically. For small numbers, I'd do something like this: Select everything from the Activity table, check for every entry if the member is a friend of John's (in the Followers table) and, if so, display the message, ORDER BY `id` DESC. But, this is very inefficient, I guess, for larger numbers (I can't even think about how many queries would take to do this on a site like Twitter...). Any ideas of how to do the same thing more efficiently? Thank you. Hi all, I've been trying to improve the speed of my file download script and was wondering if anyone could advise me which of the following is more efficient (Don't worry its not the whole script, just one segment), in terms of speed and server load? The way I have the segment currently: //if file exists need to check authorision levels //set access to no $access = NULL; //retrieve current user levels $cpm = $_SESSION['MM_CPMGroup']; $cpmh = $_SESSION['MM_CPMHGroup']; $cm = $_SESSION['MM_CMGroup']; $cj200 = $_SESSION['MM_CJ200Group']; $cj = $_SESSION['MM_CJGroup']; //set file category type & set access if allowed if ($category == 'cpm') { if ($cpm == '1') { $access = 1; if ($subcategory == 'techdata') { $path = "files/techdata/cpm/"; } elseif ($subcategory == 'msds') { $path = "files/techdata/cpm/msds/"; } elseif ($subcategory == 'symbols') { $path = "files/symbols/cpm/"; } else { $path = "files/cpm/"; } } } elseif ($category == 'cpmh') { if ($cpmh == '1') { $access = 1; if ($subcategory == 'techdata') { $path = "files/techdata/cpmh/"; } elseif ($subcategory == 'msds') { $path = "files/techdata/cpmh/msds/"; } elseif ($subcategory == 'symbols') { $path = "files/symbols/cpmh/"; } else { $path = "files/cpmh/"; } } } elseif ($category == 'cm') { if ($cm == '1') { $access = 1; if ($subcategory == 'techdata') { $path = "files/techdata/cm/"; } elseif ($subcategory == 'msds') { $path = "files/techdata/cm/msds/"; } elseif ($subcategory == 'symbols') { $path = "files/symbols/cm/"; } else { $path = "files/cm/"; } } } elseif ($category == 'cj200') { if ($cj200 == '1') { $access = 1; if ($subcategory == 'techdata') { $path = "files/techdata/cj200/"; } elseif ($subcategory == 'msds') { $path = "files/techdata/cj200/msds/"; } elseif ($subcategory == 'symbols') { $path = "files/symbols/cj200/"; } else { $path = "files/cj200/"; } } } elseif ($category == 'cj') { if ($cj == '1') { $access = 1; if ($subcategory == 'techdata') { $path = "files/techdata/cj/"; } elseif ($subcategory == 'msds') { $path = "files/techdata/cj/msds/"; } elseif ($subcategory == 'symbols') { $path = "files/symbols/cj/"; } else { $path = "files/cj/"; } } } if ($access < 1) { // if user access not granted to file category return message if($logging > 0){ $status = "Wrong Permissions"; include('logit.php'); } if (! $_SESSION['PrevUrl']) { //header("Location: ". $loginpage ); exit; } $redirect = $_SESSION['PrevUrl']; header("Location: ". $redirect ); exit; } // if file exists and user access granted continue Obviously the above is a lot of lines of code... So I have rewritten the above to look like: //if file exists need to check authorision levels & retrieve current user levels if ($category == 'cpm' && $_SESSION['MM_CPMGroup'] == '1') { $access = 1; } elseif ($category == 'cpmh' && $cpmh = $_SESSION['MM_CPMHGroup'] == '1') { $access = 1; } elseif ($category == 'cm' && $cm = $_SESSION['MM_CMGroup'] == '1') { $access = 1; } elseif ($category == 'cj200' && $_SESSION['MM_CJ200Group'] == '1') { $access = 1; } elseif ($category == 'cj' && $_SESSION['MM_CJGroup'] == '1') { $access = 1; } else { $access = NULL; } if ($access == NULL) { // if user access not granted to file category return message $status = "Unauthorised"; include('logit.php'); header("Location: ".$_SESSION['PrevUrl']); exit; } // if file exists and user access granted continue switch($subcategory) { case "techdata":$path="files/techdata/".$category."/".$filename; break; case "msds": $path="files/techdata/".$category."/msds/".$filename; break; case "symbols": $path="files/symbols/".$category."/".$filename; break; default: $path="files/".$category."/".$filename; } The second version is a lot shorter, but is it better? And could I shorten the if statement further so its more like: //if file exists need to check authorision levels & retrieve current user levels if (($category == 'cpm' && $_SESSION['MM_CPMGroup'] == '1') || ($category == 'cpmh' && $cpmh = $_SESSION['MM_CPMHGroup'] == '1') || ($category == 'cm' && $cm = $_SESSION['MM_CMGroup'] == '1') || ($category == 'cj200' && $_SESSION['MM_CJ200Group'] == '1') || ($category == 'cj' && $_SESSION['MM_CJGroup'] == '1') { $access = 1; } else { $access = NULL; } if ($access == NULL) { // if user access not granted to file category return message $status = "Unauthorised"; include('logit.php'); header("Location: ".$_SESSION['PrevUrl']); exit; } // if file exists and user access granted continue switch($subcategory) { case "techdata":$path="files/techdata/".$category."/".$filename; break; case "msds": $path="files/techdata/".$category."/msds/".$filename; break; case "symbols": $path="files/symbols/".$category."/".$filename; break; default: $path="files/".$category."/".$filename; } Any advice would be appreciated! Thanks!! |