So, I'm using a mix of PHP and HTML to display the results of a text file search query. On the previous page, there's a set of forms for a license plate number, start date, and end date. In theory, if the text file contains the license plate within the listed dates, it will show what time, date, and location all of them are shown in an unordered list. The code create the list without items initially, regardless of whether or not there's any matches. If there's matches, it creates a list item for each match. If not, it creates a single list item that says no matches were found.
Currently, however, it's trying to do both if there's no matches. If there's no number matching in the database, it'll create a mostly blank line for the "match," then display the message that there was no matches.
Here's an example of the current, wrong output:
Query results for :
, : .
There are no plates found matching the query.
Here's the code that's creating this. I've looked it over for an hour now and can't figure out why it's doing that.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8" />
<title>Query</title>
<link rel="Stylesheet" media="all" href="styles.css" />
</head>
<body>
<div class="match">
<h1>Query results for <?= $wantedplate ?>: </h1>
<ul>
<?php
$wantedplate = $_GET["plate"];
$data = fopen("stored.txt", "r");
$cline = fgets($data);
$match_check = 0;
list($cplate,$cdate,$ctime,$place) = explode(",",$cline);
while ( !feof($data) ) {
list($cplate,$csubject,$cdate,$ctime,$cplace) = explode(",",$cline);
if ($cplate == $wantedplate) {
$match_check += 1;
?>
<li> <?= $cdate ?>, <?= $ctime ?>: <?= $cplace ?>.</li>
<?php
;
$cline = fgets($data); }
else {$cline = fgets($data); }
}
if ( $match_check == 0 ) { ?>
<li> There are no plates found matching the query. </li>
<?php ; } ?>
</ul>
</div>
</body>
</html>
Any help that could be provided would be greatly appreciated. I've been staring at this for an hour now and still can't figured out why it's doing that. Thanks in advance for the assistance.
Related
These are my problems:
Note: the single queotes (') are not actually displayed
echo $variable; returns nothing
echo "$variable" returns '$variable'
returns 'stuff"; code ?'
this problem appears both in a portable version of Chrome and in Firefox
here is my code for reference:
<!DOCTYPE HTML>
<html lang = "it" >
<head>
<meta charset="utf-8">
<meta name = "keywords" content = "catcher, gioco, top, 10">
<meta name="author" content="Luca Ballarati">
<?php require 'connessione'; ?>
<title> TOP 10 </title>
</head>
<body style = "background-color: white;">
<h1>PROVA:</h1>
<?php
apri_conn();
mysqli_select_db($con,"catcher");
$sql="SELECT Username, Record FROM utenti ORDER BY Record LIMIT 10";
$result = mysqli_query($con,$sql);
chiudi_conn();
echo '<b><center><h2>TOP 10 GIOCATORI e RECORD</h2></center></b><br><br>.';
?>
<?php
$i=0;
while ($i < 11) {
$i++;
$NomeUtente = mysql_result($result,$i,"NomeUtente");
$Record = mysql_result($result,$i,"Record");
$str = "AAA"
echo "<p>AAA</p>";
}
?>
</body>
I think I'm using the correct syntax, from the comparisons I made with other posts on this site and others. Am I wrong, or is there something else at play?
Apart from you numerous errors contained within this code, you shouldn't use echo on a HTML document, you can simply close the PHP tag. For example
if( 1 == 1 ) { //True every time
?>
<p>AAA</p>
<?php } ?>
is almost the same as you would write :
if( 1 == 1 ) { //True every time
echo "<p>AAA</p>";
}
Also if you want to mix HTML with PHP code, I would advise you to use endif and endwhile for your loops.
I am trying to set a condition for php- mysql pagination so that it can change the current page "li" to "li class="active" " to mark the current selected page. I am new to php and searching for such pagination tutorial but no luck.
I have done so far what is working but not able to mark selected page. Here $id is for detecting the current page id. How can I set if condition ( or other) so that I can mark the current page item in the pagination? Thousands thanks for helping me.
<ul class="pagination">
<?php if($id > 1) {?> <li>Previous</li><?php }?>
<?php
for($i=1;$i <= $page;$i++){
?>
<?php
if ($id>1)
{ ?>
<li class="active"><?php echo $i;?></li>
<?php }
?>
<!-- <li><?php echo $i;?></li> -->
<?php
}
?>
<?php if($id!=$page)
//3!=4
{?>
<li>Next</li>
<?php }?>
</ul>
You could change your for loop from
<?php
for($i=1;$i <= $page;$i++){
?>
<?php
if ($id>1)
{ ?>
<li class="active"><?php echo $i;?></li>
<?php }
?>
<!-- <li><?php echo $i;?></li> -->
<?php
}
?>
to:
<?php
for($i=1;$i <= $page;$i++){
$class=($i==$id)? ' class="active"' : '';
echo '<li'.$class.'>'.$i.'</li>';
}
?>
If I've understood your code properly, $page represents total pages and $id represents the current page, this will set the current page number as the active class and leave the other pages without the class
Assuming that $id is the current page number, and that $page is the total number of pages, you need to highlight only one by doing the following in your loop:
if($i==$id) // highlight
else // don’t highlight
Your main errors are that you didn’t test whether $i==$id, and you didn’t have an alternative unhighlighted version.
I really think that you should simplify your code by separating your logic from the HTML. It becomes very unreadable otherwise, and very hard to manage.
I have taken the liberty of doing just that. This way you can see where the logic does the hard work, an you only need to print the results in the HTML.
<?php
$id=3; // test value
$page=20; // test value
$li=array(); // temporary array for convenience
$template='<li%s>%s</li>';
if($id>1) $li[]=sprintf($template,'',$id-1,'Previous');
for($i=1;$i<=$page;$i++) {
if($i==$id) $li[]=sprintf($template,' class="active"',$i,$i); // Current
else $li[]=sprintf($template,'',$i,$i);
}
if($id<$page) $li[]=sprintf($template,'',$id+1,'Next');
$li=implode('',$li); // convert to string for printing
?>
<ul class="pagination">
<?php print $li; ?>
</ul>
You will also see two techniques to make things easier:
I use an array as a temporary container. It is easier to add items this way and then to implode it into a string afterwards
sprintf makes it easier to define a template string, so you can manage the HTML component more easily, and fill in the gaps when the time comes.
I have a webpage called search.php
I want it to have a title/tab tag that looks like this:
<head>
<title><?php echo $number_count; ?> items found - Mysearch </title>
<head>
But the variable $number_count is 0 until later php scripts are called to query the database and display the items one at a time. At the end of the HTML I can easily display <p> <?php echo $number_count; echo "items found" ?> </p> and it works with the correct count.
It must be defined first.
Best (and only in this case) approach to do it is to do calculations first, then generate website output.
EDIT:
You can do it like that:
<?php
$count = 125;
?><!DOCTYPE html>
....
<title>Title count: <?php echo $count ?></title>
....
I've read and heard it is really sensible to separate your PHP and HTML tags as much as possible. Now my question is how should I do that? I couldn't really find the answer so I decided to ask you.
I was thinking about to use the POST function.
Check out my code:
<div class="aftelklok rondenSB">
<a href="?page=agenda">
<?php
// countdown function
// parameters: (year, month, day, hour, minute, seconds)
countdown(2013,2,24,18,0,0);
function countdown($year, $month, $day, $hour, $minute, $seconds)
{
// make a unix timestamp for the given date
$the_countdown_date = mktime($hour, $minute, $seconds, $month, $day, $year, -1);
// get current unix timestamp
$today = time();
$difference = $the_countdown_date - $today;
if ($difference < 0) $difference = 0;
$days_left = floor($difference/60/60/24);
$hours_left = floor(($difference - $days_left*60*60*24)/60/60);
$minutes_left = floor(($difference - $days_left*60*60*24 - $hours_left*60*60)/60);
$seconds_left = floor($difference - $days_left*60*60*24 - $hours_left*60*60 - $minutes_left*60);
if($difference > 0){ echo "Nog ".$days_left." dagen ".$hours_left." uur .$minutes_left." minuten tot de dienst"; }
else{ echo "De vorige dienst is afgelopen."; }
}
?>
</a>
</div>
So what i want is just the echo but then have all the php code not in my div but above the html code. like:
<?php ..... ?>
<html>
<body>
echo
</body>
</html>
As pemeon said, Smarty is quite a smart (pun intended) approach for that.
If you want to learn more about the backgrounds, you might want to google for "Model-View-Controller in php" or something like that. Basically, it's about separating your view (all the presentation stuff, e.g. HTML) from your code logic (controller) and your data objects / sources (model).
Smarty is nice but you'll need a bit of learning time to figure out how the template engine is designed, how to use it and how to apply it to your specific challenges.
If you don't want such a big solution at the moment and want to start a bit smaller and easier, you could write your own very simple template "engine" around the functions file_get_contents(...) and str_ireplace. The idea looks like this: You put your HTML stuff in template-files (for example *.html or *.tpl file ending) that don't contain any php code but place holders for dynamically created content:
Example: main-layout.tpl
<html>
<head><title>${Title}</title></head>
<body>
<img src="yourfancylogo.png" alt="Header logo"><br>
Here some navigation | ... | ... <br>
${Content}
<hr>
<div id="footer">© 2013 John Doe - Contact us</div>
</body>
</html>
Example: welcome.tpl
<h1>Hello, ${Username}! Nice to see you!</h1>
<p>So your username is ${Username}? Then you might want to read our terms of service before starting to use our app:</p>
<pre>${TOS}</pre>
Example: tos-document.txt
1) An apple a day keeps the doctor away!
2) No Smoking!
3) ...
In your php script you do something like this:
<?php
$template = file_get_contents('main-layout.tpl');
if (isset($_GET['requestedpage'])) {
// Parameter given!
$requestedPage = $_GET['requestedpage'];
} else {
// No page parameter. Assume "home".
$requestedPage = "home";
}
$username = "Monty"; // get from session data
if ($requestedPage == 'home') {
// -- begin handler code for page "home" --
$title = "Start Page - Welcome";
$content = file_get_contents('welcome.tpl');
$tos = file_get_contents('tos-document.txt');
$content = str_ireplace('${TOS}', $tos, $content);
// -- end handler code for page "home" --
} else if ($requestedPage == 'aboutus') {
...
} else {
$title = "Page Not Found - Error";
$content = file_get_contents('error404.tpl');
$content = str_ireplace('${PageThatWasNotFound}', htmlentities($requestedPage), $content);
}
$output = str_ireplace('${Content}', $content, $template);
$output = str_ireplace('${Title}', htmlentities($title), $output);
$output = str_ireplace('${Username}', htmlentities($username), $output);
die($output);
?>
Using such a separation of the template and the data to insert, you can later modify your layout / template without having to touch your php scripts. For example, if you want to modify your header or footer shown on all pages, you have a single point of change as you can modularly assemble your site from several template-bricks.
To keep the php source above readable, while your source is becoming larger, you can put all the handler codes into separated php files. You'd include them by include or require into your main source file.
But watch out: You have to escape all placeholder values that might come from user inputs - regardless, if you get them from a database or directly from $_GET or $_POST (-> XSS vulnerabilities). All input is evil!
You cannot use a php function or variable outside of a PHP block. However, it is possible to store a value in a php variable then use it in a tiny PHP block.
For example:
<?php
// ...
$foo = 42;
// ...
?>
Then
<html><body>
<p>Answer is <?php echo $foo; ?></p>
</body></html>
or
<html><body>
<p>Answer is <?= $foo; ?></p>
</body></html>
You could put your php in a separate file, and then use include or require.
do_stuff.php:
<?php
// some calculations
echo "stuff";
?>
Then in your html...
index.php:
<html>
<body>
<?php include 'do_stuff.php'; ?>
</body>
</html>
About include
The best way is to use some template engine like smarty or twig. If you do not have time to learn you can for now just write code at the top and when you want to use some calculations in i.e you use .
<?php
// calculations
$foo = 'foo';
?>
<html>
<body>
<div><?=$foo?></div>
</body>
</html>
And when you start to use this kind of 'separation' (php code in the top of the file) and html at the bottom and you will use this shortcut version of the echo function, you will easily transform into using template system.
The goal should not be keeping php away from html code, the goal should be keeping business logic from presentation logic. One of the ways to do this is utilising a Model-View-Controller layout, or you could use one of many other paradigms. The main point of this approach is making changing one part independent of the other: imagine creating a separate mobile or json front end, that does all the exact same logic, but outputs it completely differently. If the business logic and presentation logic are completely entangled, you will have a hard time, probably needing to both reproduce or blatantly copy code, as well as creating two different branches that need to be kept in-sync, making maintaining it a nightmare.
I`m using right now this sort of frame, its sort of like the frame MrSnurb made, but then in HTML in stead of php. what do you think about this framework guys?
<?php
if(isset($_GET['page'])) {
$page = $_GET['page'];
}else{
$page = "home";
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Younited - <?php echo $page; ?></title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/slides.min.jquery.js"></script>
</head>
<body>
<div class="container ronden">
<?php
include "partials/header.php";
include "partials/menu.php";
?>
<div class="content">
<?php
if (file_exists("partials/pages/".$page.".php")) {
include "partials/pages/".$page.".php";
}
else{ echo "<p>De pagina <b>".$page."</b> bestaat niet.</p>";
}
include "partials/sidebar.php";
?>
</div>
</div>
<?php
include "partials/footer.php";
?>
</body>
</html>
Use some template engine like smarty. To create template of your html code and push there varibles.
So I decided to give codeigniter a chance and convert my existing site which is all custom php to the codeigniter framework. But trying to figure out how to do this best in codeigniter that I was doing from my original site. In the original site a person would visit a page such as index.php. In the index.php code its broken into sections like so (This is just a very simple example):
index.php:
<html>
<head></head>
<body>
<div id="top">{$SECTION1}</div>
<div id="main">{$SECTION2}</div>
<div id="bottom">{$SECTION3}</div>
</body>
</html>
Then in my main php file that is included in every single page I run a query that grabs all "modules" that are assigned to each section above for the index.php page. So give me all modules that are assigned to {$SECTION1}, {$SECTION2} and {$SECTION3} for index.php. A module in my original system is simply a php file that does a specific job so I might have a module called latest_story.php and in the script it gets the last 10 stories from the database and display the results.
latest_story.php
include('class/story/story_class.php');
$story = new Story($databaseconn);
$latest_story = $story->findLatestStory(10);
//If results back from $latest_story loop through it
//and display it however I want
Then using output buffering I execute each module then take the outputted information from each module assigned to each section and replace that section with the outputted data.
Can this be done in codeigniter? If so can someone point me in the right direction in doing this in codeigniter?
EDIT
To give a more clear view of what Im doing in the original system I run a query on every single page to determine what "modules" to grab for the current page the person is viewing then run this code
foreach($page_modules AS $curr_module)
{
$module_section = intval($curr_module->section);
$module_file = $global_function->cleanData($curr_module->modfile);
$module_path = MODS .$module_file;
if(is_file($module_path))
{
ob_start();
include($module_path);
${'global_pagemod' .$module_section} .= ob_get_contents();
ob_end_clean();
}
}
Then I simply take each variable created for each section and replace {$SECTION[n]} with that variable in the template.
ADDITIONAL EDIT
What Im trying to do is be able to create "modules" that do specific tasks and then in the backend be able to dynamically place these modules in different sections throughout the site. I guess you can say its like wordpress, but a more simplier approach. Wordpress you can add a module and then assign it to your pages either in the left column, middle or right column. Im trying to do pretty much the same thing.
Basically, Codeigniter is an MVC framework. To use it, you really want to embrace that rather than include files. You can rejig your code as:
In your controller:
function example()
{
$this->load->model('story_model','story');
$data['section1'] = $this->story->latest();
$data['section2'] = $this->story->top_stories(5);
$data['section3'] = $this->story->most_popular();
$this->load->view('example', $data );
}
In your model:
function latest()
{
return $this->db->limit(1)->get('stories');
}
etc.
In your view:
<html>
....
<div id="latest">
<h2><?php echo $section1->title; ?></h2>
<?php echo $section1->body; ?>
</div>
<div id="top">
<?php foreach $section2 as $popular { ?>
<h2><?php echo $popular->title; ?></h2>
<?php echo $popular->body; ?>
<?php foreach} ?>
</div>
</html>
If you wanted a second page, with different content but the same layout, you'd add this to your controller:
function second_page()
{
$this->load->model('tags_model','tag');
$this->load->model('authors_model','author');
$data['section1'] = $this->tag->latest();
$data['section2'] = $this->tag->top_tags(5);
$data['section3'] = $this->author->most_popular();
$this->load->view('example', $data );
}
and add in new models etc.
You can pass the retrieved data as an array to the main view and then access that data on the subviews.
For example:
Main View
$posts = $this->post_model->fetch_all();
$top_data = $this->more_data_model->fetch_more_data();
$data = array('posts'=>$posts,'top_data'=>$top_data);
$this->load->view('main_view',$data);
Then on the main view you load the subviews:
$data = array('data_name'=>$top_data);
$this->load->view('top_view',$data);
And then on the subview you just use the data however you want. There might be a more effective way to do this, but i believe this'll do the trick. :)
I do it like this:
Controller:
function about()
{
$user_session = $this->model_user_lite->Session_Check();
$data['auth'] = $user_session;
$user_id = $this->model_user_lite->Session_UserID();
$data['user_id'] = $user_id;
$this->load->view( 'main_about.php', $data );
}
View:
<? $this->load->view('header_base.php'); ?>
<? $this->load->view('include_standart.php'); ?>
<? $this->load->view('header_standart.php'); ?>
<div class="box">
<div class="box-top"></div>
<div class="box-center">
<div class="content">
<center>
<h2><?= lang('MAIN_ABOUT_CAPTION_TEAM'); ?></h2>
<div class="hr"></div>
...
Header Base:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="shortcut icon" href="<?= base_url(); ?>/favicon.ico" type="image/x-icon">
<link rel="icon" href="<?= base_url(); ?>/favicon_animated.ico" type="image/x-icon">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta property="fb:admin_id" content="677920913" />
<meta property="fb:app_id" content="<?= FACEBOOK_APPID; ?>" />
<meta property="og:site_name" content="<?= SITE_NAME; ?>" />
<?php if ( empty( $og_title ) === FALSE ): ?>
<meta property="og:title" content="<?= $og_title; ?>" />
<?php endif ?>
...
This way you have a clean file system, seperate header, you can even have more headers just as you like, and can assign all the data from the controller to the view.
**Variables that are assigned from the controller, also go to views loaded by your "main view".
I'm using it in a major dating website and it works like a charm.