Include functions - php

EDIT
Due to the overwhelming amount of advice I have received, I have fixed my problem. (After realizing the horrible php code I had written.) :D
Thanks to all!
Is there a reason that a function that is inside an included php file won't work on the parent page? I have two functions inside a php file that is included at the top of the page. However, when I try to call the function, it doesn't do anything. Here's the basic layout:
Main page:
<?php include 'includes/header.php'; ?>
<?php getPosts();?>
<div>Some HTML Code</div>
<?php endPosts(); ?>
Header.php
function getPosts() {
$result = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
};
function endPosts() {
} /*End while statement */
};
Any idea why this won't work? I'm getting a blank white screen right now.

That code is so not valid. Why are you declaring a function inside of another function? And there aren't supposed to be semicolons on the end of function declarations/loops. The first thing to do is to enable error reporting.

I don't think that kind of stripping in functions will work. Aren't you getting errors from the PHP parser?
You should use something like this:
<?php $res = getPosts() ?>
<?php while ($item = mysql_fetch_array($res)): ?>
<div>Some HTML code</div>
<?php endwhile; ?>
With your getPosts() function like:
function getPosts()
{
$query = mysql_query("SELECT * FROM posts order by id desc");
if (!$query) die('MySQL error');
return $query;
}

I think you are missing the core understanding of what a function is. Variables inside one function cannot be accessed by another function unless passed into the function.
Also you can not start a procedural statement (while loop) in one function and end it within another function.

You're essentially trying to create a parameterless function named endPosts for each row in posts. I don't even know what you're trying but this won't work. You can't declare a function twice.
And even if you could, endPosts doesn't do anything, so even if this would be valid code, it wouldn't output anything (except for the div).

That's not really how PHP works. After including the header file, PHP will see something like this:
<?php
function getPosts() {
$result = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
};
function endPosts() {
} /*This is just an empty function */
}; /*And here is where getPosts ends*/
?>
You seem to be confused between what includes and function calls achieve.
What I think you want to be doing is something like:
<?php
getPosts();
while($row = mysql_fetch_array($result)) {
?><div>Some HTML Code</div><?php
}
?>

Related

Changing font colors in PHP when calling a function

<?php
echo get_menu_tree(0);
?>
Here's my PHP tag wherein I'm calling a function that displays all the data (text) from PHP MySQL Database.
The default color when I'm calling the function is white. How do I change the font color into Black?
I just updated my post. Here's my return function. Any ideas?
<?php
function get_menu_tree($parentID)
{
global $con;
$menu = "";
$sqlquery = " SELECT * FROM category where parentID='" .$parentID . "' ";
$res=mysqli_query($con,$sqlquery);
while($row=mysqli_fetch_array($res,MYSQLI_ASSOC))
{
$menu .="<li><a href='index.php?page=category&categoryID=".$row['categoryID']."'>".$row['name']."</a>";
$menu .= "<ul>".get_menu_tree($row['categoryID'])."</ul>"; //call recursively
$menu .= "</li>";
}
return $menu;
}
?>
Thank you!
<?php
function get_menu_tree($parentID)
{
global $con;
$menu = "";
$result = mysqli_query($con, "SELECT * FROM category WHERE parentID = '$parentID'");
while($row = mysqli_fetch_assoc($result)) {
$menu = "<li><a href='index.php?page=category&categoryID =".$row['categoryID']."'></a></li>";
}
$menu = "<ul>".$menu."</ul>";
return $menu;
}
?>
But if you want to output a table with the data i personaly would just use a php file and use this code
<?php
//Define $con here and put the php scripts you need in this file or use require(path/to/file.php) or include(path/to/file.php) to include other php documents
?>
//Some HTML...
<ul>
<?php
$result = mysqli_query($con, "SELECT * FROM category WHERE parentID = '$parentID'");
while($row = mysqli_fetch_assoc($result)) {
echo "<li><a href='index.php?page=category&categoryID =".$row['categoryID']."'></a></li>";
}
?>
</ul>
Let me be a little more generic instead of going straight to the point:
You can think at PHP as a lnaguage to manipulate text effectively and the kind of text you can manipulate is quite generic: in fact you can use PHP to produce any kind of text, also C, C++, ... code even if it is typically used in the Web context hence to produce HTML and CSS
As a result of this, PHP in itself has no understanding of the text it's manipulating, from its perspective it's just text
What you are interested in (color of an element) is something that is defined at CSS level, not at PHP level, however PHP is the tool you can use to produce CSS
To be slightly more complete (and conclude) this Appearance Semantic is defined at CSS level and requires HTML to define the structure first: the example provided by #TSteffenmann is in fact a specific case of this and it's hence correct but you can do something even more generic (i.e. instead of a span you can use p, ... whatever you want and use CSS to style)

Using html code in php function or no?

i would to know what is good practice for writing code to put all HTML code inside PHP function and in my front index.php file just call function to show code.
class.php:
public function test() {
$sql='select id,title from test ';
$nem=$this->db->prepare($sql);
$nem->execute();
$nem->bind_result($id,$title);
echo '<ul class="centreList">';
while($nem->fetch())
{
echo '<li>'.$id.'<a href="'.$title.'" >Download</a></li>';
}
echo '</ul>';
}
index.php:
<?php $connection->test(); ?>
This work fine, but I would like to know is this proper way or is not a good practice to use html code inside PHP functions?
It's ok to build HTML within PHP, but I would not echo to the screen directly from within the function. Instead, return the built HTML string.
$html = '<ul class="centreList">';
while($nem->fetch())
{
$html .= '<li>'.$id.'<a href="'.$title.'" >Download</a></li>';
}
$html .='</ul>';
return $html
The function should not be responsible for pushing content to the browser because it really limits what you can do with your code. What if you wanted to further process the HTML? What if you run into a condition later in the code and decided to abort? What if you wanted to set some response headers later? Some content would already be gone so none of these things would be possible without clever workarounds.
In general you want to separate your responsibilities: I would even break things down further:
one piece of code is in charge of retrieving info from the DB and returning
Another piece is in charge of building the HTML string
A third piece is in charge of displaying the HTML (probably your index.php)
New index.php
<?= $connection->test(); ?>
Do not use echo to print the html directly, wrap the html within while loop surrounded by php tags
public function test() {
$sql='select id,title from test ';
$nem=$this->db->prepare($sql);
$nem->execute();
$nem->bind_result($id,$title);
return $nem;
}
<ul class="centreList">
<?php $res = test()->fetch();
while( $res->fetch() ) { ?>
<li> <?php echo $id ?> Download </li>;
<?php } ?>
</ul>

PHP and jQuery removing dynamic list item

I hope someone will be able to shed some light on why I am having this issue. I have created a basic list that is generated from a MySQL database using a PHP class. I am then trying to use some basic jQuery to remove a list item. I could not get it working for a long time eventually finding that if I moved the jQuery include to the end of the HTML file it works but not with it included at the top of the script as I would normally aim to do. I had thought that the jQuery document ready function should have resolved this but it is not for some reason.
Here is the jQuery (very basic as said):
$(document).ready(function(){
$(".completeButton").click(function(){
$(this).closest('li').remove();
});
});
Here is the HTML page body (notice I have the jQuery include near the end rather than in the header where it does not work and remove the item, it works fine with it here though?):
<?php
session_start();
if(isset($_SESSION['user'])) {
include "header.php";
?>
<h2>Task List</h2>
<?php
include_once "DatabaseConn.php";
include_once "taskList.class.php";
$sql = "SELECT `GV_Employee`.`requests`.`req_ID` , `GV_Employee`.`equipment`.`description` , `GV_Employee`.`employees`.`first_name`, `GV_Employee`.`employees`.`last_name`
FROM requests
RIGHT JOIN equipment
ON requests.eq_ID=equipment.eq_ID
RIGHT JOIN employees
ON requests.emp_ID=employees.emp_ID
ORDER BY requests.req_ID;";
$stmt = $db->prepare($sql);
$stmt->execute();
$results = $stmt->fetchALL();
foreach ($results as $row){
$task[] = new tasklist($row);
}
foreach($task as $item){
echo $item;
}
?>
<script src="tasklist.js"></script>
<?php
}else {
session_destroy();
header("Location: http://dunc2/dylanr/Starters&Leavers/index.php");
//header("Location: http://192.168.0.4/Starters&Leavers/index.php");
exit;
}
?>
Here is the class for the dynamic list:
<?php
class taskList {
private $taskData;
public function __construct($task){
if(is_array($task))
$this->taskData = $task;
}
public function __toString(){
return '<li id="task-'.$this->taskData['req_ID'].'" class="taskList">
<div class="text">'.$this->taskData['first_name'].' '.$this->taskData['last_name'].
' requires: '.$this->taskData['description'].'</div>
<div id="button">
Complete
Priority
</div>
</li>';
}
}
?>
I hope this question makes sense, I tried searching the forum but could not find a topic which covered this exact situation apologies if there is one.
Many thanks
James

Moving JavaScript into PHP

I'm just starting out with PHP, and I am attempting to move some jQuery ajax into PHP. Here is my PHP file:
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT * FROM agency ORDER BY name";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$id = $row['id'];
$name = $row['name'];
echo "<li class=\"agency\">$name<ul class=\"agency-sub\"></ul></li>";
}
include 'closedb.php';
?>
Here is my current js function:
//Add Agency content
$("ul.top-level").on("click", "li.agency a", function (event) {
if($(this).next().length) {
var numbs = $(this).attr("href").match(/id=([0-9]+)/)[1];
showContentAgency(numbs, this);
} else {
$(this).closest('ul').find('a').removeClass('sub-active');
}
event.preventDefault();
});
And here is the showContentAgency(); function:
function showContentAgency(id, elem) {
$.post("assets/includes/contentAgency.php?id=id", {
id: id
}, function (data) {
$(elem).addClass("nav-active").parent().find("ul").html(data).show();
});
}
What I'd like to do is have PHP render the unordered list rather than have jQuery insert it. This is how it is currently featured in the above PHP file:
echo "<li class=\"agency\">$name<ul class=\"agency-sub\"></ul></li>"
So I would like the PHP to populate the <ul class="agency-sub"> list.
The structure of your code is a little bit unclear to me, but the broad outline is this: You take whatever function is generating the content in contentAgency.php and call that to get the HTML, then stick that inside when you're building up the list.
Php can not access the DOM of the page like Jquery can. If you wanted to access the DOM with Php, you would have to parse the entire web page, which is probably impractical for what you want to do. Php can only modify the page before it is loaded by the browser. If you want to run code after page load, you have to use javascript.
We might be able to help you more if you post more of your code, as we currently don't know what the page's code looks like.
Is this a list inside list?
By the way you can write php code like below, it is more readable
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT * FROM agency ORDER BY name";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$id = $row['id'];
$name = $row['name'];
echo "<li class='agency'><a href='contentAgency.php?id=$id'>$name</a><ul class='agency-sub'></ul></li>";
}
include 'closedb.php';
?>
if you are using double quotes in echo you can use single quotes inside.
I'm uncertain as to what exactly you want but it sounds like you're looking for the 'foreach' loop. When I wanna populate a list of stuff from a result set i simple use:
<ul>
<? foreach($result as $object) ?>
<li><?=$object?></li>
<? endforeach; ?>
</ul>
foreach acts a for loop but doing all the logic in the background. Hope this helps.

php within a php statement

Using Wordpress, i have a plugin that inserts a playable MP3 on the page.
To call that, along with the track details, this code is inserted;
<?php if (function_exists("insert_audio_player")) {
insert_audio_player("[audio:http://thewebsite.com/thetrack.mp3|artists=Artist|titles=Titles]");
} ?>
I would like to make this editable from the backend easily, by entering some meta-data. So this;
<?php meta('track-url'); ?>
Along with other various details would replace those that are above.
Unfortunately for me, this;
<?php if (function_exists("insert_audio_player")) {
insert_audio_player("[audio:<?php meta('track-url'); ?>|artists=Jack Presto|titles=Track 1]");
} ?>
obviously does not work! This is down to my lack of understanding if PHP - can anyone help?
Cheers!
Simple! Do this:
<?php if (function_exists("insert_audio_player")) {
$trackUrl = meta('track-url');
insert_audio_player("[audio:$trackUrl|artists=Jack Presto|titles=Track 1]");
} ?>
I can't tell if the meta() function prints to the screen or returns a string. If it returns a string, do:
<?php
if (function_exists("insert_audio_player")) {
insert_audio_player('[audio:' . meta('track-url') . '|artists=Jack Presto|titles=Track 1]');
}
?>
If it prints to the screen, it's a bit more complicated. Ideally, you would have a function that DOES return a string, but as a quick hack (if you're only getting paid for a quick fix) you could do something like
<?php
if (function_exists("insert_audio_player")) {
ob_start();
meta('track-url');
$meta = ob_get_contents();
ob_end_clean();
insert_audio_player("[audio:$meta|artists=Jack Presto|titles=Track 1]");
}
?>

Categories