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.
Related
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>
So I have a html table that is automatically generated after passing a query to my database. I want to create a hyperlink within my html table to a page that will pull more detailed information from a Second Table.
I was thinking of using the Tablecell creator that pulls from the First Table, and modifying so that it would encompass the table's contents with hyperlink tags. I was thinking it would look like this.
foreach(new TableRow(new AutoArrayMaker($stmt->fetchAll()) as $rowend => $row){
echo <a href = "the reusable HTML Page">;
echo $row;
echo </a>;
}
Is my idea sound from a coding standpoint?
Firstly, echo's need to be in quotation marks " So that code wouldn't fire.
There are a few ways you can output HTML. The first is using echo's:
echo "Google";
Notice how I put a back-slash before hand? This is what is known as an escape. This puts the character after into a letter depending on what it escapes to. See php docs: http://php.net/manual/en/regexp.reference.escape.php (as my description of it was poor)
The other option would be to run out of php then join back on so to speak:
<?PHP
foreach(new TableRow(new AutoArrayMaker($stmt->fetchAll()) as $rowend => $row){
?>
<a href="abc">
<?PHP echo $row; ?>
</a>
<?PHP
}
However, this is not advised.
Edit:
Also, you can make your own table very simply:
<table>
<?PHP
foreach($stmt as $row){
?>
<tr>
<td>
<a href="abc"><?PHP echo $row[id]; ?>
</td>
</tr>
<?PHP
}
?>
</table>
See https://www.w3schools.com/html/html_tables.asp for more info.
I am coming from Asp.net world, where everything is so modular that it creates headaches and nausea sometimes and you forget what you were actually doing.
Here in PHP I was trying to study how to display tabular data, and the solution was very simple but that looked very hasty, because if I write lots of code then it will become haywire.
So my question is what standard should I follow to work with repeating data, if there is any? Please guide me to some quality material to study because I tried but did not find anything. I have studied this link.
[Edit]
The way asp.net render tabular data is by using GridView. here you just create an instance of the GridView class and send it the data retrieved from the database and remain job is done behind the scene without messing the C# or VB code with html or writing the same logic again and again. I mean it is nice example of code resuability and I want to utilize something similar here in php to write the repeating code once and then inherit it if I want it somewhere else.
I myself have migrated from ASP.NET to php and one word of advice is forget what ever you learnt in ASP.net as ASP.net abstracts a lot of thing in web development to a point you forget that you are working with basic html/jscript and http. but again, this is just a personal opinion.
Ragarding your question on how to display a table and populate it with data. Have a look at this example. Here
<?php
$people = array(
array('Tom', '16'),
array('John', '21'),
array('Kate', '19'),
array('Luke', '25')
)
?>
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr>
<td>Name</td><td>Age</td>
</tr>
<?php foreach($people as $person){ ?>
<tr>
<td><?php echo $person[0]; ?></td>
<td><?php echo $person[1]; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
I create a 2d array contain data about People and their age. Due to simplicity sake, im using a hard coded array and not retrieving data from a database.
I then use a while loop to loop through the data in the array and for each tuple, I add a <tr> in the table. This is something like a repeater in ASP.NET
DEMO
Just noticed you want a modularized version. Here is an example:
index.php
<?php
include('inc.datasource.php');
$people = DataSource::getUsers();
?>
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr>
<td>Name</td><td>Age</td>
</tr>
<!-- Render rows with data -->
<?php foreach($people as $person){ ?>
<tr>
<td><?php echo $person[0]; ?></td>
<td><?php echo $person[1]; ?></td>
</tr>
<?php } ?>
<!-- End render rows with data -->
</table>
</body>
</html>
inc.database.php
<?php
class DataSource{
public static function getUsers(){
//Connect to database
//Retrieve user data
//Return user data
//Simulating the above steps for simplicity sake
$people = array(
array('Tom', '16'),
array('John', '21'),
array('Kate', '19'),
array('Luke', '25')
);
return $people;
}
}
?>
If you want to completly seperate your php from your html. I suggest you use one of the php mvc frameworks. I personally like using Laravel and CodeIgniter
I am new to API's like today new. I have learned how to simply call the twitter api xml data and pull certain things off from a post. My problem though is I can't seem to figure out how to pull off the Geo or Coordinates in the Twitter API and display it or store it as a variable.
<html>
<?php
$xmldata = 'http://twitter.com/statuses/user_timeline/allencoded.xml';
$open = fopen($xmldata, 'r');
$content = stream_get_contents($open);
fclose($open);
$xml = new SimpleXMLElement($content);
?>
<?php
$geo = $xml->status[0]->coordinates->georss:point; //<---PROBLEM POINT!!!!
?>
<body>
<table>
<tr>
<td><img src="<? echo $xml->status[0]->user->profile_image_url; ?>" /></td>
<td>
<? echo $xml->status[0]->text; ?> at <? echo $xml->status[0]->created_at; ?> by <? echo $xml->status[0]->user->name; ?>
</td>
<td>
GEO IS AT:<? echo $geo; ?>
</td>
</tr>
</table>
</body>
</html>
When I run code I get:
Parse error: syntax error, unexpected ':' in C:\inetpub\vhosts\allencoded.com\httpdocs\twitter.php on line 11
When I remove the code for line 11 everything works though.
When dealing with namespaced elements (like namespace_name:element_name), you need to tell SimpleXML to load the elements of that namespace (default is to load elements without a namespace). For that, you use SimpleXMLElement::children() (docs).
$xml = simplexml_load_file('http://twitter.com/statuses/user_timeline/allencoded.xml');
$geo = (string) $xml->status->geo->children('georss', true)->point;
echo $geo;
The first chunk of the key line there $xml->status->geo gets the first geo element of the first status element. Then we ask for the children that belong to the georss namespace (so, any georss:… elements), followed by specifying that we want the (first, only) point.
I don't think PHP parsed the XML verbatim. While georss:point is a valid node in the XML tree, that syntax means something else to PHP. Try doing a print_r() on the $xml->status[0]->coordinates value and see what it says the properties are.
I want to grab data from a mysql database by using php. The data looks something like this:
apple 3
orange 2
banana 4
I want to take the data and put it in a html table and use css to make it look pretty, but I dont want to deal with it inside <?php ?>
After I grab the
$result = mysql_query("SELECT * FROM Table");
can I reference the result variable outside the <? php ?> tags?
No. PHP can only be done in <?php ... ?> or <?= ... ?>. Use a template engine such as Smarty if you want substitution in this manner.
in short, no you cant, it is a php variable (technically a resource in this case) so you have to parse it through the php engine, which requires the php tags
echo '<table>';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr><td>'.$row['fruit'].'</td><td>'.$row['id'].'</td></tr>';
}
echo '</table>';
Short answer is no. HTML cannot deal with dynamic content.
If you want to cut down the amount of echo statements within your code you can store the html within a given variable and then make reference to it.
I find it better to do the following:
<table>
<?php foreach($result as $row): ?>
<tr>
<td><?php echo $row['fruit']?></td>
<td><?php echo $row['id']?></td>
</tr>
<?php endforeach; ?>
</table>
This provides clarity and minimizes concatenation.