PHP - Trying To Make A Simple Template System
Hey guys first of all I got 3 files -
index.php require_once('/libs/template.class.php'); $template = new Template; $template->assign("title","test"); template.php <?php echo $title; ?> template.class.php function assign($var, $val) { $var = $val; } I'm trying to assign a variable in index.php, then recall it in the template.php, how would I go about this? Thank you! Similar TutorialsHey guys, I'm starting to build a website and I was wondering wether I should use a library template engine such as smarty, or use pure php, such as this tutorial - http://www.massassi.com/php/articles/template_engines/ Basically the website will not expose any of the users/designers to the designer portion of the website. I am scratching my head wether I should use smarty or pure php, even Facebook uses smarty, from what I have heard. I need some answers. Thank you all! I've created a template system. I've got a function to assign a page (the templates are in /template/skin). It all works fine in the main root, but if I had a directory it won't work. $dir = "template/skin"; That is found in template/ I need to be able to assign the template even in directories. The current system I am using has worked so far but it has its problems. Basically I have 2 files to display forum topics. view_topics.php and topic_list_tpl.php view_topics.php defines some variables like so $template->topic_name = $row[$key]['topic_name'] then it renders the page like so $template->render('topic_list_tpl.php'); then in topic_list_tpl.php i use this to print the name of the topic <?php echo $this->topic_name; ?> which works fine. But as you know a topic list needs a header. But the render function is within a foreach loop so it displays all of the topics from the query. This poses the problem of the header being looped, which it shouldnt be. So in view_topics.php i use: $template->topic_id = $row[$key]['topic_id']; $template->first_topic_id = $row[0]['topic_id']; then in topic_list_tpl.php i can use: <?php if($this->topic_id == $this->first_topic_id) { echo the header } else { echo the topics } but the problem comes when adding a footer bar at the bottom(for the new reply link and other topic options). i can use something like $amount_of_topics = count($row); $template->last_topic_id = $row[$amount_of_topics-1]['topic_id'] and then check it like that but that wont work when using pagination as the last topic displayed isnt always going to be the last topic in the query. So another option i have is to have the header and footer bars in seperate files and call them outside of the loop. But these files would only be 2 or 3 lines each. So is this the best option? or is there an easier way of doing things? I've made a template system, but the way I've chosed to do it doesn't give me the ability to choose a design. I've posted the code below with a bad solution for my design problem. Does anyone have any suggestions how to make a very simple and smart templatesystem? I don't have any problems coding. I just need ideas :-) Code: [Select] <?php final class View implements IView { protected $filename, $variables = array(); public function __construct($filename = null, $variables = array()) { $this->filename = $filename; $this->variables = $variables; } public function __toString() { if(!file_exists($this->filename)) { throw new Exception("View does not exists."); } $content = file_get_contents($this->filename); foreach($this->variables as $variable => $value) { $content = str_replace("#{{$variable}}", $value, $content); } return str_replace("#{content}", $content, file_get_contents("design.html")); } } ?> This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=359002.0 Hi All I am trying to set up a system that where a user sets up an account the system automatically sets up a new directory and inserts template files into it. I understand mkdir is something to do with it. Does anyone know how to go about this please? thanks i need a download system like www.filehorse.com. can plz tell me how? its generate link 4 download for limited time. without giveing hot link. plztake a look and help me out
I would like to make a budget system where the user enter their preferred budget, then the system will generate a package based on the budget enter, system will generate the budget package based on the database. For example, i have 4 categories - flower, cake, hotel & bridal house user enter budget of $100, system will then check through the database, come out with a package which include each of the categories above. output should be flower:30 cake:20 hotel:30 bridal house:20 how should i do that? what math should i use? probability? Hello, I'm trying to create a file in my home dir and in my etc folder but I keep getting permission denied.
I am doing this
$myFile = "/home/ng/http/uid.txt"; im trying to make a simple template engine but am having a problem replacing the string in the content....if anyone could give me any help or pointers please <?php class Template { public function display($filename) { echo "hello"; } public function assign($variable, $value) { if (!is_array($value)) { ob_start(); $contents = ob_get_contents(); $contents = str_replace($variable, $value, $contents); ob_end_clean(); return $contents; } } } $template = new Template(); $template->display(); $template->assign("hello", "test"); ?> code above will only display hello and not test as it should I have a database table of plants, one of chemicals, one of products, one of illnesses. Each table is connected, for example lets say opium poppies. They contain the chemical morphine. Morphine is used in painkiller products. Its used to treat pain and other illnesses. On the opium poppy page, I want to list all the chemicals found in the poppy. All the products (i.e. opium, laudanum) made from the poppy. All the illnesses which are treated with the poppy. Users need to be able to edit this page, and enter chemicals, products or illnesses that are related to this plant. They also need to be able to edit the info on the page.
Making database relations is a pain in the ass with CakePHP. I don't want to waste any more time so I'm thinking maybe making it as a wordpress plugin is the way to go. How would you go about this? Is there an easier way than wordpress, like a better CMS, or framework? If I use wordpress, should I do all the DB interactions with AJAX to avoid having to interact with the DB through wordpress (this gave me massive trouble in the past since I had my data in an external db)?
Hi i did post this on another forum which i think was the wrong place so ive posted it here aswell hope that's ok Hi i am trying to implement a simple recomendation system where the user will select an answer usign Check boxes and each box will have a value 1 -4 Those values are then passed onto the next page. I am only trying to do it based on the Price firstly to break it down bit by bit as i am not a expert im realitvely new to PHP. I am having a error with this line while {$row = mysql_fetch_array($results,MYSQL_NUM)} //get the information from the database and store in a array THE FULL CODE SO IT CAN BE SEEN IN CONTEXT WITH THE REST IS : <?php $dbh = mysql_connect("localhost", "root")//THIS CONNECTS TO THE SERVER WITH YOUR DETAILS or die ('I cannot connect to the database because: ' . mysql_error());//IF IT CANNOT CONNECT, THIS ERROR MESSAGE WILL SHOW $results = mysql_select_db ("Computers");//THIS SELECTS THE CORRECT DATABASE FROM YOUR SERVER @$price = $_POST['price']; ?> <?PHP $total_price = 0; $total_ram = 0; $number_of_items = 0; $total_items=$number_of_items + 1 while {$row = mysql_fetch_array($results,MYSQL_NUM)} //get the information from the database and store in a array { $total_price = $row["Computer_price"] + $total_price ; // this should then start with 0 and keep adding the row up $total_items = $number_of_items = $number_of_items + 1; // this should do the same but with the item number }; $av_price = $total_price/$total_items ; //gives an average of the price attribute print $av_price //Price $lowav_price = 0; //sets the low price to 0 $medav_price = 0.75 * $av_price; // sets the next level to 75 % of the avarage $highav_price = 1.25 * $av_price; // sets the next level to 125% of the average <HTML> <BODY> // for the follwing bit the user will select a check box which will have a value and these are the cases for each option. //each option is set ot be either 0 - 75% of the average or 75%- 125 % of the average or 125% and above based ont he average of the Data in the table switch ($price) { case '1' : $price_low = 0; $price_high = >= $lowav_price ; print " (I would like to pay less and get less specifications) < ".$price_low."-".$price_high.">"; break; case '2' : $price_low = >=$lowav_price; $price_high = >=$highav_price; print " (I would like to pay for what I get so what I get is equivalent to the price) < ".$price_low."-".$price_high.">"; break; case '3' : $price_low = >=$highav_price ;$price_high = >=$highav_price; print " (I would prefer to Pay as much as possible to get the best computer) < ".$price_low."-".$price_high.">"; break; case '4' : $price_low = 0; $price_high = >=$highav_price ; " (I have no preference) < ".$price_low."-".$price_high.">"; break; } print ' price option = '.$price; print "<br>"; //gives the different vaules for each selection button on the input form for price ?> <strong> SELECTED CAMCORDERS </strong> <br> <table width="75%" border="1"> <tr> <td>Model</td> <td>Price</td> <td>Stabilization</td> <td>Optical zoom</td> <td>Image</td> </tr> <?PHP while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { if (($row["price"] >= $price_low) && ($row["price"] <= $price_high)) //price // if ($row["stabilization"] == $stabilizer_present) //stabilizer // if (($row["optical_zoom"] >= $zoom_low ) // && ($row["optical_zoom"]<= $zoom_high ) // && ($row_number < 5) ) //price //{ $row_number++; ?> <tr> <td align="center"><?php print $row["price"]; ?> </td> </tr> <?php //mysql_data_seek($result, 0); }//if }//while ?> </table> </body> </html> i AHVE TRIED TO ANNOTATE it so that you can see what i am trying to do wether i am or not is another question thanx for any replies Hello, I'm in need of assistance trying to get this PHP Script working and I'm hoping you'll be able to find a solution. SQL Table Format: http://pastebin.com/LUuu2pLp Code: [Select] -- -- Table structure for table `hungergames_records` -- CREATE TABLE IF NOT EXISTS `hungergames_records` ( `user_id` int(10) unsigned NOT NULL, `victories` int(32) unsigned NOT NULL DEFAULT '0', `biggest_kill_streak` int(32) unsigned NOT NULL DEFAULT '0', `most_chests_opened` int(32) unsigned NOT NULL DEFAULT '0', `total_chests_opened` int(32) unsigned NOT NULL DEFAULT '0', `lastlogin` int(32) unsigned NOT NULL DEFAULT '0', `longest_lifespan` int(32) unsigned NOT NULL DEFAULT '0', `total_lifespan` int(32) unsigned NOT NULL DEFAULT '0', `total_points` int(32) unsigned NOT NULL DEFAULT '100', `most_points` int(32) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `hungergames_users` -- CREATE TABLE IF NOT EXISTS `hungergames_users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `donor` int(32) unsigned NOT NULL DEFAULT '0', `user` varchar(40) NOT NULL, `donor_cooldown` int(100) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `user` (`user`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=12641 ; PHP Code: http://pastebin.com/aQANz0BL Code: [Select] <?php include("config.php"); $getRankQuery = "SELECT hungergames_users.id, hungergames_records.user_id, hungergames_records.victories, hungergames_records.biggest_kill_streak, hungergames_records.most_chests_opened, hungergames_records.total_chests_opened, hungergames_records.lastlogin, hungergames_records.longest_lifespan, hungergames_records.total_lifespan, hungergames_records.total_points, hungergames_records.most_points, hungergames_users.donor, hungergames_users.user FROM hungergames_records, hungergames_users WHERE hungergames_records.user_id = hungergames_users.id ORDER BY hungergames_records.total_points DESC"; $getRankResult = mysql_query($getRankQuery); //Source From: http://stackoverflow.com/questions/7704311/calculate-rank-with-points function getUserRank($searchedUserID) { $userArray = getAllUsersOrderedByPoints(); $rank = 0; $lastPoints = -1; // Never happens foreach ( $userArray as $user) { if ($user['total_points'] != $lastPoints) $rank++; if ($user['user_id'] == $searchedUserID) break; } return $rank; } while ($data = mysql_fetch_array($result)) { echo getUserRank($data["user_id"]); } ?> What am I trying to accomplish? Simple Ranking System... Basically, The total points is stored into total_points field for each user and whoever has the highest score will be Ranked #1 and count down to a the full database (Currently at 12,641 users) Now the above function getUserRank is the code I pulled from the above source listed, I think my issue relies in the function of getAllUsersOrderedByPoints(); - I've tried doing something like. Code: [Select] $row = mysql_fetch_array($getRankResult); Then adding: $userArray = $row["user_id"]; Didn't work - So if you can help me correct this than I'll be greatly appertiated. Lastly, I've tried doing: Code: [Select] $index = 1; while ($data = mysql_fetch_array($getRankQuery)) { echo $index++ . " " . $data["id"] . " ".$data["user"]." <br>\n"; } This solution works, but this solution would not work for when a "User is Search" it would count them as the highest rank 1,2,3 and wouldn't work, so either the function up there needs to be corrected or please help get a working solution, I've been googleing this issue and seems too be a common code issue with a lot people are having and not many solutions. The application that records data (Not PHP) doesn't store any data with a "Rank" table otherwise this would be a simple echo'ed out data. For a better understanding of what I'm trying to do - You may take a look at: http://justonemoreblock.com/lb/leaderboards.php Regards, Cory I have an Job, which i need some help with.
Its an ordering system.
its probably really simple to do, and i even know how i want it set up.
all databases are setup.
i cant pay much but my payment will be : 178.59 dollar
which in this point of time is calculated from 1000 dkk
the task:
an ordering system which contains:
selection menu - to select an activity, stored in an database an starting time textfield. just a normal textfield i guess a selection menu - for package selection- wich will find the packages in the package database with the matching target id for the selected Activity a textfield for amount of people participating, as a multiplier for the price. a selection menu - for additions selecting. same as the Package selector. and an price field this is in one row, where there should be a way to add these, so that its possible to get more acticity orderes + an Total amount field all this data should then be viewable in a table, which ill create, and after that be able to be send through an email that is setup in html, which ill make:) Why i need help: i took my hands full with this project, and im leaving soon for thailand, and that is why im a bit screwed;/ hope to hear from somone fast many thanks Joachim Gerber Hello, I have a simple dice system script I am using in a chat program for a website and I was wondering if someone could simply tell me how to limit the number of dice being rolled. Here are the two chunks of script that make it work: if($irc_cmd == '/d') { if($irc_cmd == $txt) { // this can only happen with a no dice - '/d' - a help request // return an explanation of the correct format $text = "dice command is /d [[n]D]s[Xm|+a|-d|/q]*"; $this->sendToUser(null, new Message($type, $this->userid, null, $text, $this->color)); return 'ok'; } // create standard failure message $invalid_msg = new Message($type, $this->userid, null, 'ERROR: invalid dice command - '.$txt.' - enter /d for help', $this->color); // remove the original command from the dice string $dicestring = str_replace($irc_cmd,'', $txt); // use lowercase versions of D and X to make parsing simpler $dicestring = strtolower($dicestring); // remove any user entered spaces $dicestring = str_replace(' ', '', $dicestring); // note that all modifiers will follow the dice spec 'nDs' // number of dice is optional e.g. 1d4 d4 and 4 all represent a single 4-sided die // if the first token is blank, then the user intended for one die e.g. /d d20 means /d 1d20 // if the is no 'd' then the user intended one die e.g. /d 20 means /d 1d20 $parts = explode('d', $dicestring); if(count($parts)>2) { // only one 'd' is allowed $this->sendToUser(null, $invalid_msg); return 'ok'; } elseif(count($parts)==1) { // if no 'D' assume '1' die $number = 1; } else { $number = (int)$parts[0]; if ($parts[0] == "") { // if $number == 0 // if no number assume '1' die $number=1; } elseif ("$number" != "$parts[0]") { // only integers allowed $this->sendToUser(null, $invalid_msg); return 'ok'; } $dicestring = $parts[1]; } if($number < 1) { // can't allow a negative number of dice $this->sendToUser(null, $invalid_msg); return 'ok'; } // check for sides and modifiers // expand the string to put spaces around all the tokens we want $dicestring = str_replace('+', ' + ', $dicestring); $dicestring = str_replace('-', ' - ', $dicestring); $dicestring = str_replace('x', ' x ', $dicestring); $dicestring = str_replace('/', ' / ', $dicestring); // explode the whole thing to create tokens $parts = explode(' ', $dicestring); // the only other tokens should be integers // allowed formats from here are s[Xm][+a][-d][/q] // we should allow any series of these in any order, applying them left to right // the first part must be the sides $sides = (int)$parts[0]; if ("$sides" != "$parts[0]") { $this->sendToUser(null, $invalid_msg); return 'ok'; } if($sides < 1) { // can't allow a negative number of sides $this->sendToUser(null, $invalid_msg); return 'ok'; } // get the user's name //$user = ChatServer::getUser($this->userid); //$name= $user['login']; // start writing the reply string $text = '*rolls* '.$number.'d'.$sides.': '; // seed the randomizer srand(time()); // with number and sides, roll the dice, adding them up $total = 0; for($i = 0; $i < $number; $i++) { $roll = (rand()%$sides)+1; if($i != 0) $text .= '+'; $text .= $roll; $total += $roll; } // now apply all the modifiers to the roll, in the order the user specified them for ($i = 1; $i < count($parts); $i+=2) { // the value needs to be an integer $value = (int)$parts[$i+1]; $v = $parts[$i+1]; if ("$value" != "$v") { $this->sendToUser(null, $invalid_msg); return 'ok'; } // the token needs to be one of the operators - otherwise abort $token = $parts[$i]; switch ($token) { case '+': // add $total += $value; break; case '-': // subtract $total -= $value; // make minimum 1 - remove this like to allow 0 and lower if ($total<1) $total=1; break; case 'x': // multiply $total *= $value; break; case '/': // divide - round up so 1d6/3 will be the same as 1d2 $total = ceil($total/$value); break; default: $this->sendToUser(null, $invalid_msg); return 'ok'; } // add the modifier to the display string $text .= $token.$value; } // and display the final result $text .= ': '.$total; // gets sent to particular room, but with users name tacked on, so a user could spoof it // at least 'msgu' looks different $this->sendToRoom(null, new Message('rpg', $this->userid, $this->roomid, $text)); return 'ok'; } and function Message($command, $userid = null, $roomid = null, $txt = null, $color = null) { $this->command = $command; if ($command == 'rpg') $this->command = 'msgu'; $this->userid = $userid; $this->roomid = $roomid; $this->color = htmlColor($color); if($command != 'rpg') { $txt = str_replace('*rolls*', 'rolls', $txt); } if(isset($txt)) { $this->txt = $this->parse($txt); } } So again all I want it to do is limit the number of dice being rolled because right now someone can do a /d 1000000d100000 and completely crash the chat for everyone. I am thinking 100 on either variable would be plenty. Thanks for your help! Hi everyone... I would like to implement a questionnaire/survey system that has only two Answers (Yes /No). Basically, this questionnaire system will be widely used on Mobile Phones. It will be looking something like this below: http://awardwinningfjords.com/2009/06/16/iphone-style-checkboxes.html Lets say a user selects a response as No (Using the above slider button for a question). That response should be recorded in the database with User Details + Time Stamp. Also, I would like to generate a report for each question (Responses of Multiple Users) and a report at a User Level for the entire questionnaire/survey (s). Can some one guide me the fastest & easiest way to achieve this? I'm a new learner of PHP. Regards Sandeep |