I have a section in my .html page where I want to run some PHP code, which reads data from a database and 'echoes' the table filled up with that information. I kinda did it object-oriented so I'm trying to keep that along the project.
I have this exact function or method in the Class (Class Servicio):
public static function listaServicios(){
$servicios = array();
$query = "";
$db = Database::getInstance();
$query = "SELECT descripcion, precio FROM servicio";
$resultado = $db->conn()->query($query);
foreach($resultado as $item){
$servicio = new Servicio();
$servicio->setDescripcion($item['descripcion']);
$servicio->setPrecio($item['precio']);
array_push($servicios,$servicio);
}
return $servicios;
}
As you can see, the function just returns an array filled up with as many objects as rows there is in the table. The PHP page would call this method, and then print the table with the selected data inside (there is no problem with this).
The thing is how can I print it in the specific section (div with id='datos') previously mentioned, which simply is:
<section class="principal">
<div id="datos">
</div>
</section>
I kinda of have an idea but I really don't know to implement it. Maybe using a document.ready function in jQuery calling the PHP code? I would really like to use this language even if it is a very tiny function in order to learn.
You can use jquery's load function to load content via a remote file into the div. But you will need to update your listaServicios to return html instead of the array.
jquery:
$(document).ready(function(){
$('#datos').load('phpfile.php');
});
phpfile.php
<?php
$serv = new Servicio();
echo $serv->listaServicios();
?>
Correct answer to your question depends on the interface of your future application you want to reach.
If you want some kind of SPA, then you should make AJAX-requests using JavaScript (jQuery or something else) and create a separate controller to response with data.
But I think in your particular case you can do everything on server side.
First of all you should add new method to your class, name f.e. render:
public static function render(){
$services = static::listaServicios();
include 'path/to/your/template.php';
}
Then inside your template.php write next:
<section class="principal">
<div id="datos">
<?php
foreach($services as $service) {
// echo your $service here as you wish
}
?>
</div>
</section>
So after calling render() PHP will render that part of template.
To access the properties of Servicio is better you construct your table in php:
<?php $servicios = Servicio::listaServicios(); ?>
<section class="principal">
<div id="datos">
<table style="width:100%">
<tr>
<th>Descripcion</th>
<th>Precio</th>
</tr>
<?php foreach ($servicios as $servicio): ?>
<tr>
<td><?= $servicio->getDescripcion() ?></td>
<td><?= $servicio->getPrecio() ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</section>
Related
In my php page I am getting a list of cities and events dynamically from a database. Then I'm passing this sql data to jquery to render a table with the data. Sample table created by jquery could be like:
<tr>
<td id='cityMumbai'>Mumabai</td>
<td id='program1Start>11/11/11</td>
<td id='program2Start'>11/15/11</td>
<tr>
Now I've come to know that DOM can be used to manipulate table structure in php.
I saw various reference, and found it is being used to create a new page. Means the created paged is saved physically.
Possible Pseudo Code:
{
<span id="eventRows">
<? $object = new DOMDocument;//it should pick this specific instance ?>
<? while($row = mysql_fetch_array($rProgList,MYSQL_ASSOC)):?>
<? // write code to check if current cityname exitst?
$td = $object->getElementById($row['cityname']);
if(!$td.exists): ?>
<tr><td id="<? echo $row['cityname'];?>"><? echo $row['cityname'];?></td></tr>
<? else : ?>
<?
//code to insert only event information in the current city object
$td.append("dfkjsdflkjasdhflkjsfh");
?>
<? endif; ?>
<? endwhile; ?>
</span>
}
Can I use DOM in PHP to modify the page output, only... replacing the task jquery is doing using PHP. Not to modify a physical copy of it.
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
So I got the following: I'm creating dynamic pages (based on the page ID (obtained through $_GET)). My page consists of a $_get check (the html may only be shown if a $_GET variable is set) and the echo'ing of a page with html tags + php variables. Things like:
<table>
<tr>
<td>Name:</td>
<td>myFunction('foo');</td>
</tr>
</table>
etc etc etc.
I include this code above myincludedfile.php into my main file with functions include and isset($_get) .
echo include 'myincludedfile.php';
This, however, not seems to work. Altough the html gets shown, the variables and functions remain text and don't get executed.
Can anyone help me out?
Change it like this:
<table>
<tr>
<td>Name:</td>
<td><?=myFunction('foo');?></td>
</tr>
</table>
That way you are actually opening a small PHP block in the template. <?= is a shorthand notation for <?php echo, although it depends on your server configuration if the shorthand is enabled.
If the function doesn't return a value, but echos it instead, you can leave out the = as well and just execute the function like this: <? myFunction('foo'); ?> or the long notation: <?php myFunction('foo'); ?>.
In general, you don't need <?php at the start of your file. It's just that everything inside <?php .. ?> tags is executed as php and the rest is considered static output.
B.t.w. you don't need to use echo when you include a file.
Here is another alternative
$myfunction = myFunction('foo');
echo <<<CODE
<table>
<tr>
<td>Name:</td>
<td>$myFunction</td>
</tr>
</table>
CODE;
include 'myincludedfile.php';
This is called the heardoc syntax http://php.net/manual/en/language.types.string.php#example-75
You will have to include the file like this:
include 'myincludedfile.php';
What you are doing, is echo'ing the php file
Look:
<?php
$html="<h1>Hello</h1>";
function hello()
{
echo "<h1>Hello</h1>";
}
function hello2()
{
?>
<h1>Hello</h1>
<?php
}
?>
All these does the same thing.
to use them, you can do the following:
<?php
hello(); // Hello
hello2(); // Hello
echo $html; // Hello
?>
I don't think i get what you need, but try to be more specefic.
I am not sure if I just have a bad structure for my code or this is a problem not normally found, but I don't even know how to start looking for a solution for my problem. I have my own simple translation script which is called like this:
<?php echo $Translate->text("Name"); ?>
It would return (and echo) a string with a keyword 'Name'. The problem is, for several reasons (name: misstranslations, report, development, translation in situ), I might want to retrieve all strings' keywords that are on a page. A simple page (example.com/campus/index.php) looks like this:
<h1> <?php echo $Translate->text(Campus); ?> </h1>
<p style="text-align:justify;">
<?php echo $Translate->text(126); ?>
</p>
<p style="text-align:justify;">
<?php echo $Translate->text(129); ?>
</p>
<a href="<?php $Link->create("campus/about"); ?>">
<h2 class="bodymenu"><?php echo $Translate->text(About); ?> </h2>
</a>
<p style="text-align:justify;">
<?php echo $Translate->text(146); ?>
</p>
<a href="<?php $Link->create("campus/learning_center"); ?>">
<h2 class="bodymenu"><?php echo $Translate->text(Learning_center); ?> </h2>
</a>
<p style="text-align:justify;">
<?php echo $Translate->text(147); ?>
</p>
<a href="<?php $Link->create("campus/residence"); ?>">
<h2 class="bodymenu"><?php echo $Translate->text(Residence); ?> </h2>
</a>
<p style="text-align:justify;">
<?php echo $Translate->text(128); ?>
</p>
And I would like to obtain in some situations: $Translations=array("Campus","126","129","About","146","Learning_center","147","Residence","128"); for further processing (EDIT) from another page.
In some cases there's much more php logic mixed in the page, in some others it's like this. There's much more logic code and classes that it's included automatically before and after every page. So, basically, I'd like to know (for this example but being able to extend it) how could I retrieve all the keywords.
I am thinking about 2 methods basically, but I don't think either is optimal. First would be to parse the php code as is using regex. Since I know the bits that I'm looking for, I thing it would be possible. Second one is that, depending on a SESSION variable, I render the html and parse it, so the echo $Translate->text(Campus); would return something like <span id="Translation">Campus</span> and then parse only the html and retrieve all the ids. Can you think about any other way to retrieve the ids before I get on this?.
PS, I DON'T want to hardcode all the id's in an array at the beginning or end of a page.
Do not reinvent the wheel by implementing a translating system. The gettext extension is there for painless, on the fly, language switching.
Basicly you write your site in a default language:
<?php echo _("Name"); ?>
Do not write <?php echo $Translate->text(147); ?>, noboby knows what that is. Write:
<?php echo _("Learning Centre"); ?>
For managing translations there is a choice of editors for Windows, Linux and Mac, POEdit for example.
Switching to a different language is easy:
public function SetDomain( $path )
{
define( 'DOMAIN', 'messages' );
bindtextdomain( DOMAIN, $path );
bind_textdomain_codeset( DOMAIN, "UTF-8" );
textdomain( DOMAIN );
}
note: if you set short_open_tags to on you can write:
<?= _("Name"); ?>
if i understood it correct,
modify your Translate class a little: add a variable which will collect all the strings you are using, like:
public $aStrings = array();
then, add in your function text($arg) something like:
$this->aStrings[] = $arg;
then you will have all the strings on page in your Translate->aStrings variable, then to print it use somethin like:
print_r($Translate->aStrings);
Subclass the Translate class with one that collects the values in an array, then use that in your page:
class MyTranslate extends Translate {
public $texts = array();
public function text($which) {
$this->texts[] = $which;
return parent::text($which);
}
}
$Translate=new MyTranslate($User->Language);
ob_start();
require('/path/to/other/page');
ob_end_clean();
var_dump($Translate->texts);
Create 2 file in english folder. ( You can specify it later but usually location for languages file in languages directory )
campus.about.php:
<?php
$lang["Name"] = "Name";
$lang["Address"] = "Address";
?>
*campus.learning_center.php*:
<?php
$lang["Learning"] = "Learning";
$lang["Residence"] = "Residence";
?>
Your Class Translate File ( root directory ):
class Translate {
public $_text= array(); // Change it into private properties coz you create
// text method for get the value, I set it public just for easy to debug it.
private $_language;
function __construct($language){ // Set Language
$this->_language= $language;
}
public function create($page){ // Get Language File
// $page= campus/about change into this campus.about
// Get language file Ex: english/campus.about.php
require($this->_language.'/'.$page.'.php');
$this->_text= array_merge($this->_text, $lang);
}
public function text($text){ // Display Keywords
echo $this->_text[$text];
}
}
$Translate= new Translate('english');
$Translate->create('campus.about');
print_r($Translate->_text);
$Translate->create('campus.learning_center');
print_r($Translate->_text);
My website consists of many products that are each contained in a div with the id content block. The link, image, background, description and price are all loaded from a mySQL table. My original plan was to save the below html code as a string and loop over the rows in the mySQL table filling the string I created with php/mySQL values.
I was wondering if I am going about this the right way, or is there a better way to create html code from php variables?
<div id="contentblock" style="background-image:url(images/$BACKGROUND.png);">
<div id="picture"><img src="$IMAGELINK"/></div>
<div id="description"><p>$DESCRIPTION</p></div>
<div id="price"><p class=price>$PRICE</p></div>
</div>
Firstly PHP is a template engine - in my experience template engines that layer ontop of PHP are only good for the simplest of cases and are easily outgrown.
Secondly the original code is as good as any method. At risk of stating the obvious to make it better abstract it into a function;
function output_block($BACKGROUND, $LINK, $IMAGELINK, $DESCRIPTION, $PRICE)
{
echo "<div id='contentblock' style='background-image:url(images/$BACKGROUND.png);'>
<div id='picture'><a href='$LINK'><img src='$IMAGELINK'/></a></div>
<div id='description'><p>$DESCRIPTION</p></div>
<div id='price'><p class=price>$PRICE</p></div>
</div>";
}
If you want to make it much better then adopt a framework, an entire admin config page is show below. All of the HTML glue is provided by the framework - the following code is real, but really to illustrate how a framework can provide a lot of the grunge work for you.
In the example below if I want to edit a single entity I'd change the TableViewEdit into a FormView and provide an instance of an entity rather than an iterable list.
$entity = new CbfConfig(); // Database entity
$page = new AdminWebPage("Site Configuration"); // Page for output
/*
* build the view
*/
$vil = new ViewItemList();
$col = &$vil->add(new ViewItem("description","Description"));
$col->get_output_transform()->allow_edit(false); // this field cannot be editted
$col = &$vil->add(new ViewItem("value","Value"));
$v1 = new TableViewEdit($entity, $vil,"admin_values"); // present as standard editable table
/*
* output the page
*/
$page->begin();
$iterable_list = CbfConfig::site_begin();
$page->add_body($v1->get_output($iterable_list,'admin_config'));
$page->end();
Id just have all my html code outside of php tags, then whereever I need a variable from php do as follows
<div id="description"><p><?php echo $DESCRIPTION; ?></p></div>
You can loop around non php code too. For example
<?php
for($i = 0; $i < 10; $i++) {
?>
<div id="description"><p><?php echo $i; ?></p></div>
<?php
} //end for loop
?>
Obviously this is just an example.
well if im without a template engine for somereason i usually do something like:
function partial($file, $args = array()) {
extract($args);
ob_start();
include($file);
return ob_get_clean();
}
Really, there are 3 ways of doing this. Use whichever is easiest for you in the context that you are using it in.
<?php
while(($row=mysql_fetch_assoc($result))!==false)
{
echo "<div>{$row['fieldName']}</div>";
}
?>
<?php
while(($row=mysql_fetch_assoc($result))!==false)
{
echo '<div>'.$row['fieldName'].'</div>';
}
?>
<?php
while(($row=mysql_fetch_assoc($result))!==false)
{
?>
<div><?= $row['fieldName']; ?></div>
<?php
}
?>