PHP - Using Smarty 2 To Show Loop In Template
Ok so i have made the page to load the data and i have my tpl file loading i just can't figure out for the life of me why it is not displaying correctly.
what it is displaying
php for the page
<?php if($Auth->isLogged()) { $aid = $Auth->loggedAid(); $limit = 10; //grab available PTC links from db output in json $db->select('*', 'ptc', 'active = 1'); if($db->returned_rows >= 1) { $username = $Auth->loggedUsername(); $time = time(); //$row = $db->fetch_assoc_all(); $smarty->assign('row', $db->fetch_assoc()); $smarty->assign('username', $username); $smarty->assign('time', $time); } else { //set var not to display ptc ads $smarty->assign("row", "No PTC are available"); } } $smarty->display('ptc_view.tpl'); ?>tpl file <!-- START content-container --> <section id="content-container" class="clearfix"> <div id="main-wrap" class="clearfix"> <div class="page_content"> <table class="table table-hover"> <tr> <th>Ad Link</th> <th>Earnings | Points</th> <th>Times Completed</th> <th>Total Visits</th> <th>Date Added</th> </tr> {foreach key=pid item=ri from=$row} <tr> <td><a href="Pages/ptcview/{$ri[0]}">{$ri[1]}</a><br/>{$ri[3]}</td> <td>{$ri[5]} | {$ri[6]} pts</td> <td>{$ri[8]}</td> <td>{$ri[7]}</td> <td>{$ri[13]}</td> </tr> {foreachelse} <tr> <td colspan="5">Sorry there are no PTC ads available right now</td> </tr> {/foreach}can someone please show me where i have gone wrong? BTW the db table does exist and there is 1 record in it. Similar Tutorialshey guys i have this code to grab info from database in my inv.php file
$dbConn = new DBConnection(); $i = new dbHandler($dbConn, 'inventory'); $inv = array(); $sel=mysql_query("select * from inventory"); while($row=mysql_fetch_array($sel)) { $inv[] = $row; } $smarty->assign('inventory', $inv); // Finally, display the actual page $smarty->display('InvViewAdd.tpl');How to i make it show the info on my InvViewAdd .tpl page? also if i put $inv = $i->showInv(); Why smarty won't find my template file?
Fatal error: Uncaught --> Smarty: Unable to load template file 'test.tpl' <-- thrown in C:\xampp\htdocs\testing\includes\smarty\sysplugins\smarty_internal_templatebase.php on line 129also did testinstall $smarty->testInstall(); Smarty Installation test... Testing template directory... C:\xampp\htdocs\testing\templates\frontend\default\tpl is OK. Testing compile directory... C:\xampp\htdocs\testing\templates_c\frontend is OK. Testing plugins directory... C:\xampp\htdocs\testing\includes\smarty\plugins is OK. Testing cache directory... C:\xampp\htdocs\testing\cache is OK. Testing configs directory... C:\xampp\htdocs\testing\configs is OK. Testing sysplugin files... ... OK Testing plugin files... ... OK Tests complete.And get template dir var_dump($smarty->getTemplateDir());array(1) { [0]=> string(55) "C:/xampp/htdocs/testing/templates/frontend/default/tpl\" } File schema htdocs -- testing -- incluses -- smarty plugins sysplugins Smarty.class.php SmartyBC.class.php -- configs configs.php -- db connect.php db.php -- configs -- cache -- templates -- frontend -- default -- css -- mages -- js -- tpl test.tpl -- backend -- templates_c -- frontend index.phpindex.php <?php ini_set('display_errors', 1); ini_set('log_errors', 1); ini_set('display_startup_errors', TRUE); ini_set('error_log', dirname(__FILE__) . '/error_log.txt'); error_reporting(E_ALL); ob_start(); session_start(); require 'includes/smarty/Smarty.class.php'; require 'includes/db/db.php'; require 'includes/configs/configs.php'; $page = isset($_GET['do']) ? $_GET['do'] : ''; switch($page){ case 'home'; include 'pages/home.php'; break; default: include 'pages/test.php'; break; } ob_flush(); ?>configs.php <?php $smarty = new Smarty(); $smarty->compile_check = true; $smarty->debugging = false; $smarty->cache = 1; $smarty->setTemplateDir('C:/xampp/htdocs/testing/templates/frontend/default/tpl'); $smarty->setCompileDir('C:/xampp/htdocs/testing/templates_c/frontend/default'); $smarty->setCacheDir('C:/xampp/htdocs/testing/cache'); $smarty->setConfigDir('C:/xampp/htdocs/testing/configs'); ?>test.php <?php //$success = 'Success Message'; //$error = 'Error Message'; $errors[] = 'Error one'; $errors[] = 'Error two'; $smarty = new Smarty; //$smarty->assign('success', $success); //$smarty->assign('error', $error); $smarty->assign('errors', $errors); $smarty->display('test.tpl'); ?>test.tpl {if !empty($errors)} <div id="errors"> {section name=i loop=$errors} {$errors[i]}<br /> {/section} </div> {/if} So why would one use a php template engine like smarty, other than to seperate the code from html? Is this method preffered for creating larger web applications with php?
OK guys please bear with me as this is going to be a little long post. Thanks in advanced for all the help i can get. Ed I am sorry i am a noob on all this. Now on to the problem. I have on my server the aMember script installed and as some of you guys know it works with CSS and Smarty Template Engine. the Signup page is been constructed by three files .. Signup.php which in turn displays the signup.html page in my templates folder. Signup.html load or includes header.html from the same folder. Now on the header.html i put the code of the <head> tag like always <script src ...> loading all the JS libraries. But the libraries actually do not get loaded. I am uploading the three files here in a ZIP file so you guys can have a look at them and try to tell me what am i doing wrong and you guys can point me in the right direction. On the server side i am using Centos 5.5 with apache and php 5 and mySQL server. The html folder is owned not by apache but by another group. Inside the html folder the normal folders including the SMARTY folder templates and templates_c (for temporary cache files) The signup.php page is on the root folder calling the signup.html from templates and this one includes the header at the same time. All the page are CHMOD 644 and the JS are residing in a root folder named JS where all the .js files are. All the .js files are CHMOD 644 as well. Please help me ASAP. Thanks Ed Hi all, The below example is a workable code, taken from tutor_profile.sql table Code: [Select] <?php $query = "SELECT tutor_id, religion_id FROM tutor_profile WHERE tutor_id = '" . $_GET['tutor_id'] . "'"; $data = mysqli_query($dbc, $query) or die(mysqli_error($dbc)); // The user row was found so display the user data if (mysqli_num_rows($data) == 1) { $row = mysqli_fetch_array($data); print_r($row); if ($row != NULL) { $religion_id = $row['religion_id']; $tutor_id = $row['tutor_id']; } else { echo '<p class="error">There was a problem accessing your profile.</p>'; } } <!--Religion--> <tr> <td class="label">Religion:</td> <td> <select id="religion_id" name="religion_id"> <option value="1" <?php if (!empty($religion_id) && $religion_id == '1') echo 'selected = "selected"'; ?>>Buddhism</option> <option value="2" <?php if (!empty($religion_id) && $religion_id == '2') echo 'selected = "selected"'; ?>>Christianity</option> <option value="3" <?php if (!empty($religion_id) && $religion_id == '3') echo 'selected = "selected"'; ?>>Hinduism</option> <option value="4" <?php if (!empty($religion_id) && $religion_id == '4') echo 'selected = "selected"'; ?>>Islam</option> <option value="5" <?php if (!empty($religion_id) && $religion_id == '5') echo 'selected = "selected"'; ?>>Taoism</option> <option value="6" <?php if (!empty($religion_id) && $religion_id == '6') echo 'selected = "selected"'; ?>>Others</option> </select> </td> </tr> ?> As you can see I have hard coded the names of the religion in html code example - <option value="3" <?php if (!empty($religion_id) && $religion_id == '3') echoselected = "selected"'; ?>>Hinduism</option> And if our record shows that the tutor has previously selected '3', it will reflect as 'hinduism' in his profile. View profile.jpg for example example - <option value="3" <?php if (!empty($religion_id) && $religion_id == '3') echo 'selected = "selected"'; ?>>Hinduism</option> In fact, these names can be found in another table called religion.sql, but I hard coded it anyway, without using loop (while function), since there are only 8 names Code: [Select] <!--Religion--> <tr> <td class="label">Religion:</td> <td> <select id="religion_id" name="religion_id"> <option value="1" <?php if (!empty($religion_id) && $religion_id == '1') echo 'selected = "selected"'; ?>>Buddhism</option> <option value="2" <?php if (!empty($religion_id) && $religion_id == '2') echo 'selected = "selected"'; ?>>Christianity</option> <option value="3" <?php if (!empty($religion_id) && $religion_id == '3') echo 'selected = "selected"'; ?>>Hinduism</option> <option value="4" <?php if (!empty($religion_id) && $religion_id == '4') echo 'selected = "selected"'; ?>>Islam</option> <option value="5" <?php if (!empty($religion_id) && $religion_id == '5') echo 'selected = "selected"'; ?>>Taoism</option> <option value="6" <?php if (!empty($religion_id) && $religion_id == '6') echo 'selected = "selected"'; ?>>Others</option> </select> </td> </tr> Currently I am facing an issue, I guess I will need to use looping, as there are 22 names in another table which I will need to call forth, tutor_educational_level.sql, and the number of names get more and more in other tables. My question is, how do I pull out the entire list of names into a drop down box and yet showing the selected name which the user has chosen, more elaboration can be seen in profile.jpg. In profile.jpg - as you can see the list of names are shown in the drop down box and the system is able to decipher the chosen name. Another Example 1) N level 2) O level 3) A level 4) University User selected '3', which is A level, and system would still show the list of educational_names in a drop down box,, but selecting A level as the one to appear. Example 1) N level 2) O level 3) A level (selected) 4) University It should have the same overall result as the religion which I have stated above, however this time round, it is using looping function (while) to retrieve the entire list of names, select and show the name which the user has chosen Below is my code, and I know it is wrong, but generally would like to relate my idea across. Code: [Select] <?php <!--Teaching Credentials--> <tr> <td class="label">Teaching Credentials:</td> <td> <?php echo '<select name="educational_level" id="educational_level">'; $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die(mysqli_error($dbc)); $query = "SELECT tp.educational_id, el.educational_name AS educational_name, el.educational_id AS list_educational_id " . "FROM tutor_profile AS tp " . "INNER JOIN * tutor_educational_level AS el USING (educational_id) " . "WHERE tp.tutor_id = '" . $_GET['tutor_id'] . "'"; $sql = mysqli_query($dbc, $query) or die(mysqli_error()); while($data = mysqli_fetch_array($sql)) { echo'<option value="'.$data['list_educational_id'].'">'.$data['educational_name'].'</option>'; if (!empty ($data['educational_id']) && ($data['educational_id']) == ($data['list_educational_id'])) { echo 'selected = "selected"'; } } echo '</select><br/>'; mysqli_close($dbc); ?> </td> </tr> ?> This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=333337.0 Hello all; My site is at: http://www.designtoprint.com The problem is that it looks great in everything but Internet Explorer. In I.E., it's utterly broken. I think this has a lot to do with the fact that the former developer who worked on it did everything in Smarty. I'm wondering if there's a way to automate the process of recombining all the Smarty pages back into normal .php files. Or barring that, if any of you smarter-than-me people know off the top of your heads why my site is breaking in I.E., but nothing else. Thanks! Kyle Hello, I am trying to take a calendar script and use it on my site that uses Smarty templates. I have gotten all of it to work minus one spot! I am having trouble trying to get the code below to output what I want in Smarty... I have tried many things but to no avail! Any help would be appreciated! Thanks!! Obviously I want the html output from these PHP calls but I cant figure it out! Thanks for your help! for($i=0; $i< $total_rows; $i++) { for($j=0; $j<7;$j++) { $day++; if($day>0 && $day<=$total_days_of_current_month) { //YYYY-MM-DD date format $date_form = "$current_year/$current_month/$day"; //echo $date_form_good = '<td'; //check if the date is today if($date_form == $today) { $class_today = ' class="today"'; } //check if any event stored for the date if(array_key_exists($day,$events)) { //adding the date_has_event class to the <td> and close it $event_today = ' class="date_has_event"> '.$day; //adding the eventTitle and eventContent wrapped inside <span> & <li> to <ul> $event_title = '<div class="events"><ul>'.$events[$day].'</ul></div>'; } else { //if there is not event on that date then just close the <td> tag $no_event = '> '.$day; } $close_tag= "</td>"; } else { //showing empty cells in the first and last row $mts = '<td class="padding"> </td>'; } } $close_row = "</tr><tr>"; } Hi there, I wonder if anyone can help me. I'm trying to install smarty. The problem I'm having is in choosing the correct path directory for- require('/usr/local/lib/php/Smarty/Smarty.class.php'); Granted I am relatively new to coding. I've tried using- <?php echo $_SERVER['DOCUMENT_ROOT']; ?> which returns- /usr/local/apache/htdocs I think the problem is in understanding what my local directory is. In my ftp program, the first folder looks like this firstfolder/ public_html/ ( < I've installed smarty in this one) DO_NOT_UPLOAD_HERE.txt When I run a test file index.php, I get the following error- Warning: require() [function.require]: open_basedir restriction in effect. File(/usr/local/public_html/lib/php/Smarty/Smarty.class.php) is not within the allowed path(s): (/home/:/usr/lib/php:/tmp) in /home/a4808331/public_html/index.php on line 4 What I've put in my index.php file so far which I'm sure is wrong is- require('/usr/local/public_html/lib/php/Smarty/Smarty.class.php'); If you need more info I'd be happy to supply. Thanks in advance for your help. I am using X cart and I have tried add function that hide price until customers log in. so I added following codes to my files with notepad but I am keep getting smarty errors Error: Smarty error: [in customer/main/products_t.tpl line 161]: syntax error: 'if' statement requires arguments (Smarty_Compiler.class.php, line 1270) in /home1/lemielfa/public_html/include/lib/smarty/Smarty.class.php on line 1092 Here's Smarty.class.php line 1092 ------------------------------------------------------------------------------------------------------------------------------------- * @param string $error_msg * @param integer $error_type */ function trigger_error($error_msg, $error_type = E_USER_WARNING) { (line1092----->)trigger_error("Smarty error: $error_msg", $error_type); } /** * executes & displays the template results -------------------------------------------------------------------------------------------------------------------------------- This was my first time adding some code to my web, I hope I didn't screw up that much...... Thank You David ---------------------------------------------------------------------------------------- Following Code ADDED /b] 1. Apply following SQL statements either from your cart admin/patch area or myphpadmin. This will place 2 controls in General Settings / General options in Common options. The first one will allow you to turn this mod on/off Code: INSERT INTO `xcart_config` (`name`, `comment`, `value`, `category`, `orderby`, `type`, `defvalue`, `variants`, `validation`) VALUES ('cflsys_hide_prices', 'Hide prices for non-logged in customers (this will also hide quantity box, "buy now" and "add to cart" buttons)', 'N', 'General', 75, 'checkbox', 'N', '', ''); INSERT INTO `xcart_config` (`name`, `comment`, `value`, `category`, `orderby`, `type`, `defvalue`, `variants`, `validation`) VALUES ('cflsys_hide_prices_message', 'Show this optional message if the option "Hide prices" is enabled', 'You need to login in order to see prices and place orders.', 'General', 76, 'text', '', '', ''); 2. Add to init.php at the end of the file just before PHP Code: # # WARNING ! # Please ensure that you have no whitespaces / empty lines below this message. # Adding a whitespace or an empty line below this line will cause a PHP error. # this PHP Code: # added by CFL Systems for hide prices if customer not logged in $smarty->assign("cflsys_hide_prices",$config['General']['cflsys_hide_prices']); $smarty->assign("cflsys_hide_prices_message",$config['General']['cflsys_hide_prices_message']); # added by CFL Systems for hide prices if customer not logged in 3. In skin1/customer/main/products.tpl find Code: {if $config.Appearance.products_per_row && ($featured eq "Y" || $config.Appearance.featured_only_multicolumn eq "N")} {include file="customer/main/products_t.tpl"} {else} {include file="customer/main/products_list.tpl"} {/if}and before add Code: {* added by CFL Systems to hide prices if customer not logged in *} {if $login eq "" && $cflsys_hide_prices eq "Y"} {if $cflsys_hide_prices_message ne ""} <div style="color: red; margin: 5px 0; padding: 5px 5px 5px 10px; border: 1px solid #cccccc;">{$cflsys_hide_prices_message}</div> {/if} {/if} {* added by CFL Systems to hide prices if customer not logged in *} 4. In skin1/customer/main/product.tpl (skin1/customer/main/product_details.tpl for 4.3.x, code may be slightly different) find this Code: <tr> <td class="property-name product-price">{$lng.lbl_price}:</td> <td class="property-value"> and before add Code: {* added by CFL Systems to hide prices if customer not logged in *} {if $login eq "" && $cflsys_hide_prices eq "Y"} $nbsp; {else} {* added by CFL Systems to hide prices if customer not logged in *} then find Code: {if $product.forsale ne "B"} <tr> <td colspan="2"> {include file="customer/main/product_prices.tpl"} </td> </tr> {/if}and after add Code: {* added by CFL Systems to hide prices if customer not logged in *} {if} {* added by CFL Systems to hide prices if customer not logged in *} then find Code: <tr> <td class="property-name product-input"> {$lng.lbl_quantity}and before add Code: {* added by CFL Systems to hide prices if customer not logged in *} {if $login eq "" && $cflsys_hide_prices eq "Y"} <tr> <td colspan="2"> {if $cflsys_hide_prices_message ne ""} {$cflsys_hide_prices_message} {else} {/if} </td> </tr> {else} {* added by CFL Systems to hide prices if customer not logged in *}then find Code: {/if} </table> and before add Code: {* added by CFL Systems to hide prices if customer not logged in *} {if} {* added by CFL Systems to hide prices if customer not logged in *}then find Code: {if $product.appearance.buy_now_buttons_enabled}and before add Code: {* added by CFL Systems to hide prices if customer not logged in *} {if $login eq "" && $cflsys_hide_prices eq "Y"} $nbsp; {else} {* added by CFL Systems to hide prices if customer not logged in *}then find Code: </form>and before add Code: {* added by CFL Systems to hide prices if customer not logged in *} {if} {* added by CFL Systems to hide prices if customer not logged in *} 5. In skin1/customer/main/products_list.tpl find Code: {if $product.product_type eq "C"} {include file="customer/buttons/details.tpl" href=$url} {else}and after add Code: {* added by CFL Systems to hide prices if customer not logged in *} {if $login eq "" && $cflsys_hide_prices eq "Y"} $nbsp; {else} {* added by CFL Systems to hide prices if customer not logged in *} then find Code: {/if} </div> <div class="clearing"></div>and before add Code: {* added by CFL Systems to hide prices if customer not logged in *} {if} {* added by CFL Systems to hide prices if customer not logged in *} 6. In skin1/customer/main/products_t.tpl find Code: <tr> {foreach from=$row item=product} {if $product} <td class="product-cell product-cell-price"> {if $product.product_type ne "C"} {if $active_modules.Subscriptions ne "" && $product.catalogprice} and before add Code: {if $login eq "" && $cflsys_hide_prices eq "Y"} <tr> <td colspan="2"> </td> </tr> {else} {* added by CFL Systems to hide prices if customer not logged in *}then find at the end of the file Code: {/foreach} </table> {/if}and before add Code: {* added by CFL Systems to hide prices if customer not logged in *} {if} {* added by CFL Systems to hide prices if customer not logged in *} I have a serialized array stored in a database field in the following format: Unserialized: '1' => '5000', '2' => '2000' Serialized: a:2:{i:1;s:4:"5000";i:2;s:4:"2000";} The key is a database ID and the value is just a number. Next I have a table which stores some information about each ID |ID|NAME|DESCRIPTION|ENABLED?| ----------------------------------------------------- 1 | Test | Description goes here| TRUE 2 | Hello | World | TRUE What I want to do is fetch the serialized values from database, unserialize them and then loop through them using the smarty template engine. The thing is that I want to include some more information, that fetched from the database, based on the KEY of the array. I suck at explaining crazy stuff like this so I'll just provide some images and code to help out Current I have this PHP code ( I had no idea on how to approach the problem so I just wrote stuff I thought would work ): <?php require_once ( 'common-ingame.php' ); $template->assign ( 'page_title', 'Faction Standings' ); $unserialized = unserialize ( $characterInfo['charactersREPUTATION'] ); # IE: a:2:{i:1;s:4:"5000";i:2;s:4:"2000";} $names = array ( ); foreach ($unserialized as $faction_id => $faction_reputation) { $data = mysql_Fetch_assoc ( mysql_query ( "SELECT `worldfactionNAME` FROM `world_factions` WHERE `worldfactionID` = {$faction_id}" ) ); $names[] = $data['worldfactionNAME']; } $final_array = array_combine ( $unserialized, $names ); $template->assign ( 'reputation', $final_array ); $template->display ( 'my-rep.tpl' ); Smarty Template File . TPL Code: [Select] {include file="include/header-ingame.tpl"} <h3>Faction Standings</h3> <table class='ng-table'> <tr><th>Faction</th><th>Reputation</th></tr> {foreach from=$reputation key=faction_name item=faction_reputation} <tr><td>{$faction_reputation}</td><td>{$faction_name} / 10000</td></tr> {/foreach} </table> {include file="include/footer-ingame.tpl"} Screenshot of results is attached What I want to do is add extra information, fetched from the database, to the table. My table structu |FACTIONID|FACTION NAME|FACTION DESCRIPTION| FACTION ENABLED? ( NOT USED YET)| ----------------------------------------------------------------------------------------------------------------------- 1 Horus Brotherhood Description 1 TRUE 2 Darkmist Clan Description 2 TRUE Currently all that's being displayed is the faction name, which is selected based on the array key, and the reputation value which is fetched from the array value. What I want to do is add the description column value to the table. Anyone care to help? Quote Hello, Am a newbie using PEAR packages in my coding. I installed smarty on XAMPP recently and followed the configuration process in the 'php.ini' file, labelling the path to the '\libs\' directory. Before installation of smarty, my pear packages were working fine, never received any errors. However, after installing smarty and including my template file 'config.php' with 'Auth/HTTP.php' within the same file, i gor these errors; Warning: require_once(Auth/HTTP.php) [function.require-once]: failed to open stream: No such file or directory in C:\xampp\htdocs\OReilly\pear\blog\login.php on line 10 Fatal error: require_once() [function.require]: Failed opening required 'Auth/HTTP.php' (include_path='.;C:\xampp\smarty\libs') in C:\xampp\htdocs\OReilly\pear\blog\login.php on line 10 Warning: Cannot modify header information. Headers already sent by C:\xampp\htdocs\OReilly\pear\blog\login.php on line 10 Anybody got ideas what i can do to correct this issue, thanks. I have attached my templates file 'config.php' and my login script, the one that allows users to login be fore they access results to the database called 'login.php' This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=357370.0 This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=355225.0 This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=321319.0 This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=319414.0 Hey.
So the issue I'm having is consecutive loops on semi-large arrays, over and over. Consider this array:
$firstArray = array( 'row1' => array( 'dates' => array( '2014-01-01' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-02' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-03' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-04' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-05' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-06' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-07' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), ) ), 'row2' => array( 'dates' => array( '2014-02-01' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-02' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-03' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-04' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-05' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-06' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-07' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-08' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-09' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), ) ) );Originally the data comes from ~2-3 database tables, of course. But to ilustrate the point, this is how the main array looks like. This array usually contains anywhere between 10-50 rows, each row containing at least 10 dates, with 10 key/values each. And after setting up all the data, it needs to be processed. Currently this is how a friend of mine did it.. $placeDataHere = array(); foreach($firstArray as $key => $dates) { foreach($dates as $date => $values) { foreach($values as $key => $value) { $placeDataHere['DV_' . $date]['SM_' . $key] = 'KS_' . $value; //Followed by another ~50-70 lines of processing the 3 loop's data.. ... ... .... .... .... .... .... .... } } }Obviously this isn't good practise, but we can't seem to figure out a better way of doing it, since both the data and the loops are horribly nested. This loop and setup of $firstArray is run anywhere between 10-20 times/request, due to amount of users we wish to process. So, the result is that this code can take up to over 2-3 minutes to complete, which isn't really optimal performance. In short my question is, are there any better methods of handling this with the data setup we currently have? I want to show a cookie of a referral's username on a sign up page. The link is like this, www.mysite.com/signup?ref=johnsmith. The cookie doesn't show if I go to that url page. But it does show up once I reload the page. So I'm wondering if it's possible to show the cookie the first time around, instead of reloading the page? Here is my code. // This is in the header $url_ref_name = (!empty($_GET['ref']) ? $_GET['ref'] : null); if(!empty($url_ref_name)) { $number_of_days = 365; $date_of_expiry = time() + 60 * 60 * 24 * $number_of_days; setcookie( "ref", $url_ref_name, $date_of_expiry,"/"); } else if(empty($url_ref_name)) { if(isset($_COOKIE['ref'])) { $user_cookie = $_COOKIE['ref']; } } else {} // This is for the sign up form if(isset($_COOKIE['ref'])) { $user_cookie = $_COOKIE['ref']; ?> <fieldset> <label>Referred By</label> <div id="ref-one"><span><?php if(!empty($user_cookie)){echo $user_cookie;} ?></span></div> <input type="hidden" name="ref" value="<?php if(!empty($user_cookie)){echo $user_cookie;} ?>" maxlength="20" placeholder="Referrer's username" readonly onfocus="this.removeAttribute('readonly');" /> </fieldset> <?php }
Below is my output on the browser: Student: Kevin Smith (u0867587) Course: INFO101 - Bsc Information Communication Technology Course Mark 70 Grade Year: 3 Module: CHI2550 - Modern Database Applications Module Mark: 41 Mark Percentage: 68 Grade: B Session: AAB Session Mark: 72 Session Weight Contribution 20% Session: AAE Session Mark: 67 Session Weight Contribution 40% Module: CHI2513 - Systems Strategy Module Mark: 31 Mark Percentage: 62 Grade: B Session: AAD Session Mark: 61 Session Weight Contribution 50% Now where it says course mark above it says 70. This is incorrect as it should be 65 (The average between the module marks percentage should be 65 in the example above) but for some stange reason I can get the answer 65. I have a variable called $courseMark and that does the calculation. Now if the $courseMark is echo outside the where loop, then it will equal 65 but if it is put in while loop where I want the variable to be displayed, then it adds up to 70. Why does it do this. Below is the code: Code: [Select] $sessionMark = 0; $sessionWeight = 0; $courseMark = 0; $output = ""; $studentId = false; $courseId = false; $moduleId = false; while ($row = mysql_fetch_array($result)) { $sessionMark += round($row['Mark'] / 100 * $row['SessionWeight']); $sessionWeight += ($row['SessionWeight']); $courseMark = ($sessionMark / $sessionWeight * 100); 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>" round($courseMark) "<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; I think the problem is that it is outputting the answer of the calculation only for the first session mark. How in the while loop can I do it so it doesn't display it for the first mark only but for all the session marks so that it ends up showing the correct answer 65 and not 72? |