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<r=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.
Related
So i am making a simple forum to learn some PHP with CodeIgniter, by simple i mean 1 page with posts and you can click on them to comment and view more info(Think of reddit). All the data is stored in a mySQL database. Anyways i got all the links to display on my page, but what i cant figure out is how to open a new page to show the description and comments of the post. I remember doing something similar with a long time ago, can't remember how i did that sadly.
<?php
foreach($records as $rec){
$test = $rec->PostName."<br/>";
Echo "<a href=#$test>$test</a>";
}
?>
<?php
echo '<div data-role="page" id="$test"></div>';
echo "THIS ISSSSS $test";
?>
So this is the part where i need help. Any suggestions are greatly appreciated
Well for starters you'll need to refactor your attempt at generating the links as that has issues as everyone has pointed out.
So I took the liberty to come up with some test code to demonstrate a few things.
So this is Part 1.
<?php
// Simulated Database results, an array of objects
//
// These may already be Slugs with First letter upper case, hyphenated between words
// But I will do that when generating the links.
$records = [
(object)['PostName'=>'Why I recommend reading more PHP Tutorials'],
(object)['PostName'=>'Why I should take heed of what others suggest and actually try them out before dismissing them'],
(object)['PostName'=>'What is the difference between using single and double quotes in strings'],
(object)['PostName'=>'Why everyone should know how to use their browsers View Source tool to inspect the generated HTML'],
];
foreach ( $records as $rec ) {
$test = $rec->PostName;
// This would make a good helper but Codeigniter might have something already.
// So you should go and read the manual.
echo "$test";
// The above uses " to wrap the string with escaped \" within the string
// cause you cant have both.
echo '<br>';
}
// This is only here for testing... I think.
echo '<div data-role="page" id="'.$test.'"></div>';
// The above uses single quotes to wrap the string.
echo "THIS ISSSSS $test";
Part of Part 2...
<?php
// Simulated Database results, an array of objects
//
//
// These may already be Slugs with First letter upper case, hyphenated between words
// But I will do that when generating the links.
$records = [
(object)[
'id'=>1,
'PostName'=>'Why I recommend reading more PHP Tutorials'],
(object)[
'id'=>2,
'PostName'=>'What is the difference between using single and double quotes in strings'],
];
foreach ( $records as $rec ) {
$name = $rec->PostName;
$id = $rec->id;
// The slug of the page isn't really being used here as
// we are providing the pages id for lookup via an AJAX Call.
echo "<a id=".$id." href=\"#".ucfirst(str_replace(' ','-',$name))."\">$name</a>";
echo '<br>';
}
// This is where the AJAX call fired by a click on an anchor, that sends the id
// which results in the fetching of the required details to plonk in our page-area div.
echo '<div class="page-area"></div>';
There are a number of ways to do this, but going totally basic, if we create a JS event for a click on an anchor.. Which fires an AJAX Call which posts the page id to our method that returns back the HTML of the results we want to display...
URL : http://www.sayuri.co.jp/used-cars
Example : http://www.sayuri.co.jp/used-cars/B37753-Toyota-Wish-japanese-used-cars
Hey guys , need some help with one of my personal projects , I've already wrote the code to fetch data from each single car url (example) and post on my site
Now i need to go through the main url : sayuri.co.jp/used-cars , and :
1) Make an array / list / nodes of all the urls for all the single cars in it , then run my internal code for each one to fetch data , then move on to the next one
I already have the code to save each url into a log file when completed (don't think it will be necessary if it goes link by link without starting from the top but will ensure no repetition.
2) When all links are done for the page , it should move to the next page and do the same thing until the end ( there are 5-6 pages max )
I've been stuck on this part since last night and would really appreciate any help . Thanks
My code to get data from the main url :
$content = file_get_contents('http://www.sayuri.co.jp/used-cars/');
// echo $content;
and
$dom = new DOMDocument;
$dom->loadHTML($content);
//echo $dom;
I'm guessing you already know this since you say you've gotten data from the car entries themselves, but a good point to start is by dissecting the page's DOM and seeing if there are any elements you can use to jump around quickly. Most browsers have page inspection tools to help with this.
In this case, <div id="content"> serves nicely. You'll note it contains a collection of tables with the required links and a <div> that contains the text telling us how many pages there are.
Disclaimer, but it's been years since I've done PHP and I have not tested this, so it is probably neither correct or optimal, but it should get you started. You'll need to tie the functions together (what's the fun in me doing it?) to achieve what you want, but these should grab the data required.
You'll be working with the DOM on each page, so a convenience to grab the DOMDocument:
function get_page_document($index) {
$content = file_get_contents("http://www.sayuri.co.jp/used-cars/page:{$index}");
$document = new DOMDocument;
$document->loadHTML($content);
return $document;
}
You need to know how many pages there are in total in order to iterate over them, so grab it:
function get_page_count($document) {
$content = $document->getElementById('content');
$count_div = $content->childNodes->item($content->childNodes->length - 4);
$count_text = $count_div->firstChild->textContent;
if (preg_match('/Page \d+ of (\d+)/', $count_text, $matches) === 1) {
return $matches[1];
}
return -1;
}
It's a bit ugly, but the links are available inside each <table> in the contents container. Rip 'em out and push them in an array. If you use the link itself as the key, there is no concern for duplicates as they'll just rewrite over the same key-value.
function get_page_links($document) {
$content = $document->getElementById('content');
$tables = $content->getElementsByTagName('table');
$links = array();
foreach ($tables as $table) {
if ($table->getAttribute('class') === 'itemlist-table') {
// table > tbody > tr > td > a
$link = $table->firstChild->firstChild->firstChild->firstChild->getAttribute('href');
// No duplicates because they just overwrite the same entry.
$links[$link] = "http://www.sayuri.co.jp{$link}";
}
}
return $links;
}
Perhaps also obvious, but these will break if this site changes their formatting. You'd be better off asking if they have a REST API or some such available for long term use, though I'm guessing you don't care as much if it's just a personal project for tinkering.
Hope it helps prod you in the right direction.
I am developing a simple system of sample products with Object Oriented PHP, very simple thing. So far, no problem, but I have to create a button that adds a product code recorded in the database to a form in the sidebar. I do not know to develop a shopping cart with OO PHP, and codes that I find always give error because of the call of the database, or when the data list. I've been thinking of doing for JS, any help?
sorry my bad english
I got it, first I did when I click a link step by GET and the ID Code I need after seto it in a cookie, each cookie with an ID. Then I check if cookie has registered with the IDs. Not the best and most correct, but it works (more or less). Now another problem, I need to click two times to get the result as it passes by id and need to be caught refresh = /
I think it was a bit confusing but it is the maximum that dyslexia allows me to do hehehe
Here I set up the structure with the data I have in my product page:
add
<?php
$cod_get = $_GET['cod'];
setcookie("SITENAME_cod_".$id_get."", $cod_get, time()+3600, "/","", 0);
?>
And here I have a loop checking if cookie with ids, I think it will give problems, but for now I think it works ...
Thank you all.
$produto = new produtos();
$i = 0;
$produto->selecionaTudo($produto);
$produto->selecionaCampos($produto);
while($res = $produto->retornaDados()):
$res->id;
$i++;
$get_cookie = $_COOKIE['SITENAME_cod_'.$res->id.''];
if (isset($get_cookie)) {
echo $get_cookie.', ';
}else{
echo "";
}
endwhile;
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.
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.