Can't wrap my head around Global arrays - php

I asked about this last night but the answers told me to research global arrays. After spending an entire day trying to solve this I have sacrificed my man card and I'm now seeking help. I have 3 files that work together to echo a variable $body. The 3 files are login.php, global.php, and theme.php.
The login file works as expected and displays a message that I'm already logged in when I replace $body with echo, but to incorporate my theme easily and effectively I want to use the variable $body for placement reasons. When I echo $body in the theme file nothing appears. heres a quick example of my files
Login.php
<?php
include('../tools/global.php');
$body="
some scripting here";
?>
global.php
<?php
function function1(){
global $body;
}
function1();
print_r($body);
include('../theme/default.php');
include('config.php');
?>
default.php aka theme.php file
<table border='0'>
<tr>
<td colspan='2'>
<center>bar</center>
</td>
</tr>
<tr>
<td width='10%'>
hey<br>hey<br>
</td>
<td>
hello
<?php
echo $body;
?>
</td>
</tr>
</table>
Okay so how exactly would I register the global $body so it will always echo $body in the theme file? I have tried many of different things but nothing seems to work.

Login.php includes global.php but $body is defined in Login.php only AFTER global.php was included - that's why you can't use it in global.php
If you want to use it in global.php - declare it there!

I think the advice you were given about looking into globals was probably bad advice. Globals are almost never the answer. You are also using them incorrectly. The global keyword allows you to use a global variable (defined outside a function) within a function. It's that simple. It's much better practice, though, to pass the variable into the function as an argument. When you have stuff that you want to use repeatedly throughout different files, put it in a function in an include file, instead of just the body of the include file. For instance, in global.php, you have:
<?php
function renderPage($body) {
?>
<table border='0'>
<tr>
<td colspan='2'>
<center>bar</center>
</td>
</tr>
<tr>
<td width='10%'>
hey<br>hey<br>
</td>
<td>
hello
<?php
echo $body;
?>
</td>
</tr>
</table>
<?php
}
?>
Then in login.php:
<?php
require('global.php');
$body = 'This is the login page.';
renderPage($body);
?>

Related

Fatal error when try add snippets code on functions.php Wordpress

I'm trying to make a filter in functions.php of my website in Wordpress, to show some information on the customer's invoice:
echo get_post_meta($order_id,'bairro',true) . get_post_meta($order_id,'billing_complemento',true);
I've tried the following, it's retrieving the information all together, I wanted to divide it into lines. I tried it this way:
<tr class=“bairro”>
<td><b>Bairro: </b> R$ <?php echo get_post_meta($order_id,'bairro',true) ?></td>
</tr>
<tr class=“billing_complemento”>
<td><b>Complemento: </b> <?php echo get_post_meta($order_id,'billing_complemento',true) ?></td>
</tr>
<?php
but it’s giving a fatal error on the site, I believe it’s just some kind of closure. Someone to save me there?

Opening PHP statements

So I was just wondering if it was considered bad practice to open and close PHP statements, and let me explain what I mean. I know I can make variables at the beginning of my code but I like to group stuff together.I'm not sure if making one big PHP statement with all my variables is better / worse / same as opening and closing PHP statements similar to the example below.
<html>
<head></head> <---- HTML STUFF
<?php
(php stuff where connection to mysql db goes and other variables and errors)
?>
<body>
<html> <----- HTML stuff
<?php
(php stuff to call a specific table from DB)
?>
<html> <----- HTML stuff
<?php
(php stuff to call a specific table from DB)
?>
<html> <----- HTML stuff
<?php
(php stuff to call a specific table from DB)
?>
</body>
<html>
BTW the php variables I'm talking about are specific select statement from the DB.
ACTUAL CODE: or should select statements be at beg or sep file?
<table>
<tr>
<td align="left" width="200px">
Cover: Original Total
</td>
<td width="200px" align="center">
<?php
$original = "SELECT * FROM `comic_db`.`comic_db` WHERE comic_cover=\"original\"";
$orig_con = mysqli_query($comic_connect, $original);
$orig_total = mysqli_num_rows($orig_con);
echo $orig_total;
?>
</td>
</tr>
<tr>
<td width="200px" align="left">
Cover: Variants Total
</td>
<td width="200px" align="center">
<?php
$variants = "SELECT * FROM `comic_db`.`comic_db` WHERE comic_cover=\"variant\"";
$variant_con = mysqli_query($comic_connect, $variants);
$variant_total = mysqli_num_rows($variant_con);
echo $variant_total;
?>
</td>
</tr>
<tr>
<td align="left" width="200px">
Cover: Baby Totals
</td>
<td width="200px" align="center">
<?php
$baby = "SELECT * FROM `comic_db`.`comic_db` WHERE comic_cover=\"baby\"";
$baby_con = mysqli_query($comic_connect, $baby);
$baby_total = mysqli_num_rows($baby_con);
echo $baby_total;
?>
I'm assuming the repeated <html> tags in your example are just placeholders and would actually be <div>s and other elements making up the actual content of the page.
Your example is what's commonly called "spaghetti code" because it can quickly turn into an unmaintainable mess because you can't clearly see an overview of the HTML, nor can you see all the PHP code in one place.
The main thing to keep in mind is separating application logic (such as your database queries) from presentation (HTML and presentation logic like looping over an array to display it as an HTML list).
At the very least you'd want to put the main PHP code at the top of the file like you said, but it would be much better if it was in a separate file.
P.S. Any beginner book on PHP will discuss this in detail.

jquery datatable and cakePHP

i am trying to implement jquery datatable, in my cakePHP based website, but it just wont load. this website is already half developed, and from the way i see it, the js' is loaded through a file called _head.inc.ctp located inside the views/layouts folder, i have added the datatables library inside the libs folder which is webroot/js/libs and load it inside the _head.inc.ctp file.
suppose i have this:
my controller:
var $helpers = array(
'Form',
'Html',
'Javascript'
);
//my method
function dataTable_example($id=null){
$details = $this->Detail->find("all");
$this->set('details', $details );
}
my view:
<div>
<?php echo $javascript->link('libs/jquery.dataTables.js'); ?>
<script>
$(document).ready(function(){
$('#js-datatable').dataTable();
});
</script>
<h2><?php echo __l('Tickets');?></h2>
<div>
<table id="js-datatable">
<tr>
<th>some heading 1</th>
<th>some heading 1</th>
<th>some heading 1</th>
</tr>
<?php
if (!empty($details)){
foreach ($details as $detail):
?>
<tr>
<td><?php echo $detail['Detail']['id'];?></td>
<td><?php echo $detail['Detail']['created'];?></td>
<td><?php echo $detail['Detail']['ticket_detail'];?></td>
</tr>
<?php
endforeach;
}else{
?>
<tr>
<td>No Data Found</td>
</tr>
<?php }?>
</table>
</div>
</div>
i even hard coded it using the usual call, and checked it using firebug to see if the script is loaded or not, and according to firebug, it is loaded, so i cant see whats making the script fail my table.
did i missed some steps ? please help
thanks
You don't have thead and tbody elements as required by the datatables script
You should use the find function in your controller and pass the array to the view and in the view write it.. don't just leave the table empty

How to create a custom template system in PHP

I want to use a custom template system in my php application,
What I want is I want to keep away my php codes from design, I would like to use a tpl file for designs and a php file for php codes
I dont want to use any ready maid scripts. Can any one point out some links link or useful info how to build a php templating system to achieve this
Thank you
The way I do it is to create a template file(.tpl if you wish) and insert markers which will be replaced with str_replace in PHP. The code will look something like this:
For template.tpl file
<body>
<b>Something: </b> <!-- marker -->
</body>
For the PHP
$template = file_get_contents('template.tpl');
$some_data = 'Some Text'; //could be anything as long as the data is in a variable
$template = str_replace('<!-- marker -->', $some_data, $template);
echo $template;
That's it in a nutshell but it can get a lot more complex. The marker can be anything as long as it's unique.
I want to keep away my php codes from design, I would like to use a tpl file for designs
...and mix your tpl codes with "design"!
what's the difference then? :)
PHP itself is efficient templating system.
And nowadays most developers agreed that dividing your PHP code to business logic part and display logic part is most preferable way.
It can be very limited subset of PHP of course. You will need an output operator (<?=$var?>) one, a condition <? if(): ?>...<? endif ?>, a loop <? foreach(): ?>...<? endforeach ?> and include.
An example of such a template:
<table>
<? foreach ($data as $row): ?>
<tr>
<td><b><?=$row['name'] ?></td>
<td><?=$row['date'] ?></td>
</tr>
<tr>
<td colspan=2><?=$row['body'] ?></td>
</tr>
<? if ($row['answer']): ?>
<tr>
<td colspan=2 valign="top">
<table>
<tr>
<td valign="top"><b>Answer: </b></td>
<td><?=$row['answer'] ?></td>
</tr>
</table>
</td>
</tr>
<? endif ?>
<? if($admin): ?>
<tr>
<td colspan=2>
<? if($row['del']): ?>
show
<? else: ?>
hide
<? endif ?>
edit
</td>
</tr>
<? endif ?>
<? endforeach ?>
</table>

How to properly indent PHP/HTML mixed code? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
When mixing PHP and HTML, what is the proper indentation style to use? Do I indent so that the outputted HTML has correct indentation, or so that the PHP/HTML mix looks properly formatted (and is thus easier to read)?
For example, say I have a foreach loop outputting table rows. Which one below is correct?
PHP/HTML mix looks correct:
<table>
<?php foreach ($rows as $row): ?>
<tr>
<?php if ($row->foo()): ?>
<?php echo $row ?>
<?php else: ?>
Something else
<?php endif ?>
</tr>
<?php endforeach ?>
</table>
Outputted HTML looks correct:
<table>
<?php foreach ($rows as $row): ?>
<tr>
<?php if ($row->foo()): ?>
<?php echo $row ?>
<?php else: ?>
Something else
<?php endif ?>
</tr>
<?php endforeach ?>
</table>
I've found that when I run into this situation (quite frequently), I don't have a standard style to use. I know that there may not be a "correct" answer, but I'd love to hear thoughts from other developers.
The PHP and the HTML should each be indented so that they are correct with respect to themselves in source form, irrespective of each other and of outputted form:
<table>
<?php foreach ($rows as $row): ?>
<tr>
<?php if ($row->foo()): ?>
<?php echo $row ?>
<?php else: ?>
Something else
<?php endif ?>
</tr>
<?php endforeach ?>
</table>
I often pondered this question too, but then I realized, who cares what the HTML output looks like? Your users shouldn't be looking at your HTML anyway. It's for YOU to read, and maybe a couple other developers. Keep the source code as clean as possible and forget about what the output looks like.
If you need to debug the output, use Chrome Developer Tools, Firebug, or even F12 Tools.
I generally put opening php tags at the beginning of the line, but indent whatever is inside the tags to match the html formatting. I don't do this, however, for simple echo statements since I use short-open tags. I think it makes simpler it when browsing through the file to find all the declarations.
<table>
<? foreach ($foo as $bar): ?>
<tr>
<? foreach ($bar as $baz): ?>
<td><?=$baz?></td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>
Direct answer to your question: If you need to read the HTML output often, it might be a good thing to output well indented HTML. But the more common case will be that you need to read your php source code, so it is more important that the source is easily readable.
Alternative to the two options you mentioned: See chaos' or tj111's answer.
Better still in my opinion: Don't mix HTML and php, use a template engine instead.
You can always use a bit of whitespace too to help readability. Building on chaos' indentation:
<table>
<?php foreach ($rows as $row): ?>
<tr>
<?php if ($row->foo()): ?>
<?php echo $row ?>
<?php else: ?>
Something else
<?php endif ?>
</tr>
<?php endforeach ?>
</table
The only downside with this is if you have a lot of mixed code it can make your document twice as long, which makes for more scrolling. Although if you have this much mixed code you may want to consider a templating engine.
You should not be bothered about markup indentation in the production environment. Neither should you use Tidy or other HTML purifiers. There are valid use cases, e.g. when you allow HTML input (but consider using Markdown instead), though these are rare.
Most often HTML beautifiers-filters are abused to hide the underlying issues with the code. Don't. Correct your markup manually.
If you need to indent your code only in the development environment, you can use either of the above. However, beware that these libraries will attempt to fix your markup (that's their primary purpose; indentation is a by-product). I've written Regular Expression based indentation tool Dindent.
Dindent will convert markup like this:
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
console.log('te> <st');
function () {
test; <!-- <a> -->
}
</script>
<div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div><table border="1" style="background-color: red;"><tr><td>A cell test!</td>
<td colspan="2" rowspan="2"><table border="1" style="background-color: green;"><tr> <td>Cell</td><td colspan="2" rowspan="2"></td></tr><tr>
<td><input><input><input></td></tr><tr><td>Cell</td><td>Cell</td><td>Ce
ll</td></tr></table></td></tr><tr><td>Test <span>Ce ll</span></td></tr><tr><td>Cell</td><td>Cell</td><td>Cell</td></tr></table></div></div>
</body>
</html>
To this:
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
console.log('te> <st');
function () {
test; <!-- <a> -->
}
</script>
<div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div>
<table border="1" style="background-color: red;">
<tr>
<td>A cell test!</td>
<td colspan="2" rowspan="2">
<table border="1" style="background-color: green;">
<tr>
<td>Cell</td>
<td colspan="2" rowspan="2"></td>
</tr>
<tr>
<td>
<input>
<input>
<input>
</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Ce ll</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>Test <span>Ce ll</span></td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
</table>
</div>
</div>
</body>
</html>
Dindent will not attempt to sanitise or otherwise interfere with your code beyond adding indentation. This is to make your development/debugging easier. Not for production.

Categories