Caching html from mysql query - php

Alright so I have no idea how to even begin doing this
But basically I have one of the menus that displays on every page come getting it's text and links from a mysql database.
Here's the code:
<table class="LeftMenuTable">
<?php
// Generates the left menu from the LeftMenu_items table
$result = MySqlQuery("SELECT * FROM Menu_LeftMenu;");
while ($row = mysqli_fetch_assoc($result))
{
if ((int)$row['header'] == 0)
{
// echos value is on or not
echo "<tr><td class='LeftMenu'><a href='" . $row['url'] . "'>" . $row['text'] . "</a></td></tr>";
}
else if ((int)$row['header'] == 1)
{
// header
echo "<tr><td style='border:0px; height:5px;'></td></tr>"; // adds extra empty tabel
echo "<tr><td class='LeftMenuHeader'><b><strong>" . $row['text'] . "</strong></b></td></tr>";
}
}
?>
</table>
function MySqlQuery($Query)
{
$result = $mysqli->query($Query) or die(ReportMysqlError(mysqli_error($mysqli), $Query));
return $result;
}
I feel like any sql queries that could be be replaced by html cache somehow are reducing the site's speed.
If anyone has any information or suggestions it's much appereciated.

If you were keen enough, I would suggest a slightly different approach.
If you make your pages using a templating language called "Smarty" find out more here. http://smarty.net you should find that smarty will manage the caching for you.
How is this related to your question.
It will make your web development easier as you will stop "echoing" content into your HTML.
Smarty will do the caching for you. When a smarty template loads, smarty keeps a copy of it (or you can tell it cache a file for x hours, days etc).
As you site grows smartys caching will help keep your site running and loading fast.
You have to very little work to make caching work, just use smarty templates to build your site.
Lastly you may find it a LOT simpler to build sites using smarty.
John.

In the method that calls your database (to fetch menu items and build the corresponding html):
Check if there is an item in the current $_SESSION with the html of your menu.
If (1) returns nothing, execute the query, build the html and store the results in $_SESSION.
Return the html of your menu.
A bit more information about how you can use the session can be found here.
This way, your menu query will only be fired once per session. I doubt it's a real performance breaker though (if your query is more or less in normal form).
Note that changes in your menu will not get picked up automatically before the session expires with the mechanism described above.

I usually use memcached (or some other similar solution) when I need to organize a caching layer.
But in your case may be it'd be done in a more simple way: use an intermediate 'generator' script which will be fired each time the table in question is updated (as it's updated from some form of admin panel, right?) and will generate a static file, then include this file within your main view script.

Related

Define a variable before including function in PHP, and use variable

I am Working on making the menu for our content management software using php and we are having this small issue. Since we want everything to eventually be called in chunks, were breaking certain page items into chunks and loading them via functions through an included file. Since this is hard to explain, I will post some example code of what i mean below.
This is the file page.php (removed needless html code).
This is the page the user is on:
<?php
define("CURRENT_PAGE", "page.php");
include_once("data/main.inc.php");
?><html>
Content loads here.
<? desktopMenu(); ?>
</html>
Okay and here's the function for desktopMenu() from main.inc.php:
function desktopMenu() {
// Query to get the top level navigation links with no parents
$query = mysql_query("SELECT * FROM menu WHERE p_id = '0'");
if(mysql_num_rows($query) > 0) {
while($result = mysql_fetch_array($query)) {
extract($result);
if($isparent == "1") {
// Just check if they have children items
$sub_menu_query = mysql_query("SELECT * FROM menu WHERE p_id = '$id'");
if(mysql_num_rows($sub_menu_query) > 0) {
// CODE TO SHOW THE MENU ITEM AND ITS SUBS
}
} else {
// CODE TO SHOW REGULAR MENU ITEMS
// WANT TO INSERT class='active' if the CURRENT_PAGE is this value..
echo "<li><a href='#'>link</a></li>";
}
} else {
echo "<li><a href='javascript:void(0);'>Error Loading Menu</a></li>";
}
}
I am wondering how I can get the CURRENT_PAGE on the included script so I can load the class="active" onto the correct page. I am already using the following:
$config = include('config.inc.php');
$GLOBALS = $config;
on the top of main.inc.php, above this menu function so I could set global variables and include my $config['database'] variables for calling the SQL database within a function (doesn't work otherwise).
How can I check the current_page variable so I can set it active in the menu? I have tried a few different things but nothing is showing the way we expect it to. Thanks guy.
First of all I would recommend looking at MVC architecture when building your apps. I believe the use of GLOBALS is frowned upon.
To answer your question:
Since you are defining a constant define("CURRENT_PAGE", "page.php"); then this will be globally available within the scope of the function desktopMenu()
so you may use something like:
$className = (isset(CURRENT_PAGE) && CURRENT_PAGE=='xxxxx')?'class="active"':'';
echo "<li>link</li>";
xxxx string is most likely a field output from you database as the page name which will match the defined constant.
$className = (isset(CURRENT_PAGE) && CURRENT_PAGE==$result['page_name'])?'class="active"':'';
This is the basic form and you will most likely need additional conditions for the 'active' menu switch mapping to different pages.
I've tried to answer your question with an example although the structure you have used run the app is not the recommended way to develop.
I would look at the way modern frameworks are structured (Laravel, Zend, Symphony...) and utilise these.
I would also try and automate the page mapping (e.g. look at the URL and pull out the page from a rewrite which matches to the menu in your database)
best of luck
There are multiple options. Including static functions, global variables and passing the variable or object into the function.
The consensus for various reasons is to pass the variable into the function
$myVar = new Object\Or\Data();
function myFunction($myVar) {
//do stuff with $myVar
}
//then call the function
myFunction($myVar);
There are lots of answers to this question on stackOverflow, so have a deeper search. Here is an example
I found the solution to my problem and thought I would share here. I first set the call on the page.php to use desktopMenu(CURRENT_PAGE); and then on my main.inc.php I added this line
$thispage = CURRENT_PAGE;
function desktopMenu($thispage) {
//REST OF FUNCTION
}
And I set a table variable on each menu item called menu-group, so I can define the current menu group for a menu item and have the appropriate menu item highlighted when you're on that page or one of it's sub pages.
Thanks so much for the answers guys!

How to make a webpage retain variables from form?

Sorry if I'm duplicating threads here, but I wasn't able to find an answer to this anywhere else on StackOverflow.
Basically what I'm trying to do is make a list in which variables entered in a form by a user can be kept. At the moment, I have the code which makes this possible, and functional, however the variables entered in the form only appear on the list after the user hits submit... As soon as I refresh the page or go to the page from somewhere else, the variables disappear. Is there any way I can stop this from happening?
Edit: here are the codes:
//Page 1
<?php
session_start();
$entries = array(
0 => $_POST['signup_username'],
1 => $_POST['signup_email'],
2 => $_POST['signup_city']);
$entries_unique = array_unique($entries);
$entries_unique_values = array_values($entries_unique);
echo "<a href='Page 2'>Link</a>";
$_SESSION['entries_unique_values'] = $entries_unique_values;
?>
//Page2
<?php
session_start();
$entries_unique_values = $_SESSION['entries_unique_values'];
foreach($entries_unique_values as $key => $value) {
$ValueReplace = $value;
echo "<br /><a href='http://example.com/members/?s=$ValueReplace'>" . $value . "</a><br/>";
}
?>
Your question is really quite vague. the answer depends on how much data you have to store, and fopr how long you need it to exsist.
By variable I assume you mean data the user has entered and that you want to put into a variable.
I also presume that the list of variables is created by php when the form is submitted.
Php will only create the variable list when the form is submitted as php is done entirely on the server, therefore you will not have or see the variables until the form is submitted.
if you wanted to be able to see the list as it is being created you could use javascript then once you have you php variables the javascript list isn't necesary.
each time you request a php page wheather it is the same one or not the server generates a totally new page, meaning all unhardcoded variables from previous pages will be lost unless you continually post the variables around the pages the server will have no memory of them.
You have a few viable options.
) keep passing the user created variables in POST or GET requests so each page has the necesary info to work with. Depending on the situation it might or might not be a good idea. If the data only needs to exsits for one or two pages then it is ok, but bad if you need the data to be accessable from any page on your web.
2.) start a session and store the variables in a session. Good if the data only needs to be around while the user is connected to the site. but will be lost if user close window or after a time.
3.) place a cookie. not a good idea but ok for simple data.
4.) create a mysql database and drop the variable info in there. great for permanent data. this is how i always complex user data.
just a few ideas for you to look into as it is difficult to see what you really mean. good luck.
use PHP session or store variable values in Cookies via JS or using PHP. It would be nice if you show your working codes :)
Your idea is fine, however you just need to add a little condition to your Page 1 that only set your SESSION values when POST is made, that way it will keep the values even if you refresh. Otherwise when you visit the page without a POST those values will be overwritten by blank values, which is what you are seeing now. You can modify it like
<?php
session_start();
if(isset($_POST["signup_username"]))
{
$entries = array(
0 => $_POST['signup_username'],
1 => $_POST['signup_email'],
2 => $_POST['signup_city']);
$entries_unique = array_unique($entries);
$entries_unique_values = array_values($entries_unique);
$_SESSION['entries_unique_values'] = $entries_unique_values;
}
echo "<a href='http://localhost/Calculator/form2.1.php'>Link</a>";
?>
You could use JavaScript and HTML5 local storage.

PHP Zend_Paginator on mySql query using GET

I am trying to call pages using Zend_Paginate() on a query that loads based on a GET search string the query essentially does the following:
SELECT * FROM table WHERE column LIKE '%searchstring%' OR alt_column LIKE '%searchstring%';
The query works fine when called via search/submit text form and the URL returns something similar to
URLINK.php?search=searchstring
However when trying to move onto the next page the program dumps me back to the paginate alternate URL (used for errors or no page display)-- hope this last line makes sense it is late and am doing my best to type this up with transparency.
What is the best method when using paginate against URL.php?search=searchstring"?
A bit more on the call to the url
//search query
$search = searchQuery('search', 'list_sql_rows.php');
$results - searchTable($dbRead, $search);
search method using the variables above in the order below
if(isset($_POST['submit_search'])) { $searchstring = $_POST['searchstring'];
if($searchstring) { header('Location: results.php?search=' . $searchstring); } }
This bit works well, but when I try to call the results.php?page=2 with paginator the system reverts me to the fall back URL list_sql_rows.php as mentioned above. Any thoughts/comments are appreciated.
Just to clarify a search field/form from the search.php page sends the $searchstring to the results.php page via $_POST && $_GET as fail safe. The get method sends the $searchstring in the URL header so the results of the search DO work on the first page results.php?search=$searchstring. This works just fine. The pagination seems to lose the $searchstring, and I wonder if this is due to a loss of the $_POST/$_GET when paginator begins to 'paginate' it returns URL results.php?page=2 so it seems $_GET may not be the method of choice?
UPDATE
On the write track now paginate works it is my link structure that is broken.
_results_samples.php?search=robert&page=4_ will in fact return page 4 of the paginated results using the word ROBERT
SOLUTION FOUND VIA variant suggestion by ROCKYFORD
variant of recommended method by first persisting $searchstring
change to paginate links as shown below
<a href='" . $_SERVER['PHP_SELF'] . "?search=" . $searchstring . "&page={$page}'>$page</a>
Here is the example of correct using of pagination:
in action-method:
$select = $clients->getAll();
$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
$paginator->setCurrentPageNumber($this->_getParam('page'));
$paginator->setItemCountPerPage(20);
$this->view->clients = $paginator;
in a view script:
<?php if (count($this->clients) > 0): ?>
...
<?php echo $this->paginationControl($this->clients, 'Sliding', 'partials/paginator.phtml'); ?>
<?php else: ?>
<h3 class="notice">No registered clients found!</h3>
<?php endif; ?>
But even if you will fail with this variant, you can always try to compose your own component, Zend only aids us in solving some tasks.
you need to make sure you preserve the query strings between requests, use Zend_Session_Namespace or Zend_registry.
Everytime Zend_Paginator loads a page when using the DbTableSelect or DbSelect adapters it has to hit the db with the query, it just changes the limit option.
Or you could just dump the whole query result into a Zend_Paginator_Adapter_Array and it will page through the array.
[edit]
you are going to have to persist the query string between requests someway so you can put it back in the url string, I usually use Zend_Registry, but then I use the whole MVC stack. You don't seem to be using the whole stack so you'll need another method, probably $_SESSION would work. I'm sure there are many other ways to persist this data.
P.S. you didn't mention which adapter you are using so I'm making some assumptions.
[edit]
Personally I always use $_post for this when possible to avoid all this, only seem to have this problem with $_get.

Dynamically generating page links for a CMS

I've searched far and wide and every CMS tutorial out there either doesn't explain this at all or gives you a huge chunk of code without explaining how it works. Even on stack overflow I can't find anything close to the answer, though I'd be okay with eating my words if someone could point me to the answer.
I am using PHP and mysql for this project.
I am building a CMS. Its extremely simple and I understand every concept I think I'll need except how to dynamically generate pages and page links. The way I want to do it is by having a database table that stores the name of a page and the main content of the page. That's all. Then I'd just call a script to pull the main content of a page into whatever page I happen to call. No big deal, right? Wrong.
Here's the problem. If I were to do this then I'd have to create a file for every page I want to create that calls the script that pulls the content from the correct database row. So I could add all sorts of page names and contents into the table but I don't know how to call them without manually creating new files each time I want to link to a new page.
Ideally there'd be a script that creates links to pages based on the page name row of the DB table as the pages are created. But how do you get those links with the ?=pageName at the end? If I just knew how that worked then I could figure the rest out.
UPDATE
The second answer really confirmed everything I thought I had to do but there is one catch. My plan now is to split up all the code into a series of functions and either include or require them in different templates that will be used to format the way pages are displayed. I need one look for the home page and one other design for the rest of the pages. I'm thinking that I'll have a function that says if ID is 0 then call this page template.php else call this other template file.php. But how do I pass the required variables to these new files? Do I just include the index.PHP page in them?
Bill your actually on the right track. Almost all web software today does extensive URL processing. Traditionally you would have php pages on your web root and then utilize the query string in the URL to refine the page's output. You have already arrived at why this might not be desired. So the popular alternative is the Front Controller design pattern. Basically we funnel every request to your index.php page and then route the request to internal pages or apps outside the web root. This can get complicated fast and everybody seems to implement this pattern in unique ways.
We can utilize this pattern without the routing by simply putting our app in the index page. The script below shows an example of what your trying to do in the simplest of ways. We basically have one page with our script. We can request the virtual pages by changing the id query string in our url. For example www.demo.net/?id=0 can be utilized as an index to your site. This should be the same as www.demo.net without the 'id' query. Just keep solving those problems one by one even if you don't know what the problem is. Once you start looking at other peoples code, then you can start seeing how other people solved the same problems you have.
The solution below will get you started, but then what do you do when you want an admin page? How do you authenticate the user? Do you duplicate alot of the code for yet another page? If your serious about your CMS then your going to want to implement some kind of framework underneath it. A framework to process the url, route to your application, load configuration files, and probably manage your database connection. Yea it gets complicated, but not if you solve each problem one at a time. Utilize classes or functions to share code to start. At the very least include a common "bootstrap" file at the top of your page to initialize common functionality such as a database connection. Read Stack Overflow just to keep up with whats going on. You can learn alot of terminology and probably find some answers to questions you didn't even know you wanted to ask.
Below assume we have a table with the following fields:
page_id
page_name
page_title
page_body
<?php
//<--------Move outside of web root-------------->
define('DB_HOST', 'localhost');
define('DB_USER', 'cms');
define('DB_PASS', 'changeme');
define('DB_DB', 'cms');
define('DB_TABLE', 'cms_pages');
//<---------------------------------------------->
//Display errors for development testing
ini_set('display_errors','On');
//Get the requested page id
if(isset($_GET['id']))
{
$id = $_GET['id'];
}
else
{
//Make page id '0' an index page to catch all
$id = 0;
}
//Establish a connection to MySQL
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASS) or die(mysql_error());
//Select the database we will be querying
mysql_select_db(DB_DB, $conn) or die(mysql_error());
//Lets just grab the whole table
$sql = "SELECT * FROM ".DB_TABLE;
$resultset = mysql_query($sql, $conn) or die(mysql_error());
//The Select Query succeeded, but returned 0 result.
if (mysql_num_rows($resultset)==0)
{
echo "<pre>Add some Pages to my CMS</pre>";
exit;
}
//This is our target array we need to fill with arrays of pages
$result = array();
//Convert result into an array of associative arrays
while($row = mysql_fetch_assoc($resultset))
{
$result[] = $row;
}
//We now have all the information needed to build our app
//Page name - Short name for buttons, etc.
$name = "";
//Page title - The page content title
$title = "";
//Page body - The content you have stored in a table
$body = "";
//Page navigation - Array of formatted links
$nav = array();
//Process all pages in one pass
foreach($result as $row)
{
//Logic to match the requested page id
if($row['page_id'] == $id)
{
//Requested Page
$name = $row['page_name'];
$title = $row['page_title'];
$body = $row['page_body'];
$page = "<b>$name</b>";
}
else
{
//Not the requested page
$page = $row['page_name'];
}
//Build the navigation array preformatted with list items
$url = "./?id=" . $row['page_id'];
$nav[] = "<li>$page</li>";
}
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>SimpleCMS | <?php echo $title; ?></title>
</head>
<body>
<div>
<div id="navigation" style="float:left;">
<ul>
<?php
foreach($nav as $item)
{
echo $item;
}
?>
</ul>
</div>
<div id="content"><?php echo $body;?></div>
</div>
</body>
</html>
I think you need to read about $_GET.
I also recommend a decent PHP book. Forget online tutorials; they are (for the most part) utterly useless.

Fetch database information on a new page without using new documents

I'm working on a page where I've listed some entries from a database. Although, because the width of the page is too small to fit more on it (I'm one of those people that wants it to look good on all resolutions), I'm basically only going to be able to fit one row of text on the main page.
So, I've thought of one simple idea - which is to link these database entries to a new page which would contain the information about an entry. The problem is that I actually don't know how to go about doing this. What I can't figure out is how I use the PHP code to link to a new page without using any new documents, but rather just gets information from the database onto a new page. This is probably really basic stuff, but I really can't figure this out. And my explanation was probably a bit complicated.
Here is an example of what I basically want to accomplish:
http://vgmdb.net/db/collection.php?do=browse&ltr=A&field=&perpage=30
They are not using new documents for every user, they are taking it from the database. Which is exactly what I want to do. Again, this is probably a really simple process, but I'm so new to SQL and PHP coding, so go easy on me, heh.
Thanks!
<?php
// if it is a user page requested
if ($_GET['page'] == 'user') {
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
// db call to display user WHERE id = $_GET['id']
$t = mysql_fetch_assoc( SELECT_QUERY );
echo '<h1>' . $t['title'] . '</h1>';
echo '<p>' . $t['text'] . '</p>';
} else {
echo "There isn't such a user".
}
}
// normal page logic goes here
else {
// list entries with links to them
while ($t = mysql_fetch_assoc( SELECT_QUERY )) {
echo '<a href="/index.php?page=user&id='. $t['id'] .'">';
echo $t['title'] . '</a><br />';
}
}
?>
And your links should look like: /index.php?page=user&id=56
Note: You can place your whole user page logic into a new file, like user.php, and include it from the index.php, if it turns out that it it a user page request.
Nisto, it sounds like you have some PHP output issues to contend with first. But the link you included had some code in addition to just a query that allows it to be sorted alphabetically, etc.
This could help you accomplish that task:
www.datatables.net
In a nutshell, you use PHP to dynamically build a table in proper table format. Then you apply datatables via Jquery which will automatically style, sort, filter, and order the table according to the instructions you give it. That's how they get so much data into the screen and page it without reloading the page.
Good luck.
Are you referring to creating pagination links? E.g.:
If so, then try Pagination - what it is and how to do it for a good walkthrough of how to paginate database table rows using PHP.

Categories