PHP Template system output - php

I'm using template system in php, so my code is like that for example...
$template->addVar ( 'thenameoftemplate', 'thenameofsubtemplate',"what to output");
And this code i output in the html file like... {thenamefsubtemplate}..
But i have a problem, when i try to output from database something with in the template like the above example but from database, it isn't working, only 1 output from the rows, but when echo it outside of the template it works..
I tryed to output with, foreach,while eaven with for from the database and output it in the template but it's showing just one result.
How to fix that, i wan't to row all the result and output them .
Update
Actualy i don't know what is the template system, some script was gaved to me and.. everythingwas ok until the database output..
Here is my last try with the for..
if (check_group_access_bool('show_admin_panel_button')) {
$template->addGlobalVar('admin','<BR>виж Ñмъкваните пеÑни<BR><img src="/images/icons/edit-user-32x32.png" hspace="2" alt="редактирай" align="absmiddle">редактирай');
}
$sudtwo = $_SESSION['user']['id'];
$fvsmt = mysql_query("select * from fav where user_id=$sudtwo");
if(isset($_SESSION['user']['id'])){
while($rowings = mysql_fetch_array($fvsmt)) {
$template->addVar( 'userprofile', 'userprofiletwo',"<tr><th nowrap valign=\"TOP\" align=\"LEFT\"> ñòèë: ".$rowings['name']." <form method=\"post\"><input type=\"submit\" value=\"premahni ot liubimi\" name=\"del\"></form>></th></tr>");
if(isset($_POST['del']))
{
mysql_query("DELETE FROM fav WHERE name_id=".$rowings['name_id']."");
}
echo"".$rowings['name']."<br>";
}
}
This is in the php and here is the HTML
<template:tmpl name="userprofile">
{USERPROFILETWO}
</template:tmpl>
That's how it outputs..
In the php code, where is my echo it works, but here in the html outputs only one row.

edit: OK, you're using something called patTemplate, which hasn't been updated in a few years. I found some documentation though, and once you've set up your PHP correctly, this in your html should work:
<table>
<patTemplate:tmpl name="userprofile">
{userprofiletwo}
</patTemplate:tmpl>
</table>
BUT, your PHP is a bit of a mess. What you have is basically:
for () {
$rowings = ...;
//you are overwriting the variable each time here
$template->addVar('userprofile', 'userprofiletwo', $rowings);
}
And I think what you want is something like:
$rowings = array();
for () {
// make an array of your data
$rowings[] = ...;
}
// and call addVar *once*
$template->addVar('userprofile', 'userprofiletwo', $rowings);
Now {userprofiletwo} is an array, and you can loop over that in your template.
Also, I'm not sure what the purpose of this bit of code is:
if(isset($_SESSION['user']['id'])){
}
as it doesn't really do anything...

Related

Using PHP code in the value of a variable

I am trying to send an email in PHP where the content of the email has some conditional checks and some database query lookups.
What I would like to acheive is having my email code as a variable (similar to below) so that I can sent mail() the content to the relevant people.
$emailContent = "<p>My email content</p>";
However the value of this variable would have some code like this:
<table>
<?php
$get_course_units = "SELECT * FROM course_units where course_units.course_code = {$courseCodeExtract}";
$course_units_results = $conn->query($get_course_units);
if ($course_units_results->num_rows > 0) {
while ($courseUnits = $course_units_results->fetch_assoc()) {
?>
<tr>
<td><?php echo $courseUnits["unit_code"]; ?> – <?php echo $courseUnits["unit_name"]; ?> </td>
</tr>
<?php
} //end loop for course units
} //end if for course units
?>
</table>
How should I continue?
Split up your script into an html template file and your php logic.
Use shortcodes in your templates where you want to have custom information and then use str_replace to replace that content with the actual values.
$template_string = file_get_contents('myfile.html');
$shortcodes = array("{{FNAME}}","{{LNAME}}","{{OTHER_STUFF}}");
for(/* all the people you want to mail */){
$custom_info = get_custom_info(/* person */); //eg returns assoc array
$result = $template_string;
foreach($shortcodes as $code){
$result = str_replace($code, $custom_info[$code], $result);
}
//do what you want with result and mail it
}
In the example above, get_custom_info would be returning an associative array with the same values as the shortcodes array, just for convenience.
Now anywhere I put {{FNAME}} in my html, it will be replaced with the value I get back from the custom info function.
You can easily extend this to scrape the template and look for {{ and }} (or whatever shortcode syntax you want) anddetermine what variables you will need from your custom info, shaping the query to only give you what you actually need.
Not sure if this is the best way, but it seems to work pretty well. (also best way is subjective, so might want to ask questions a little differently)

Insert a php page into div with ajax call (jquery)

This question is more about "good pratices" than a real problem; I just started with php and jquery, but I would know more in details what I'm doing and why.
What I'm trying to get: catch user request (with a form), query database and then show result in a table. All using ajax call and jquery.
Now, I have my controller.php:
class Controller {
public $model;
public function __construct() {
$this->model = new Model ();
}
public function run() {
$action = isset ( $_REQUEST ["action"] ) ? $_REQUEST ["action"] : $action = "home";
switch ($action) {
case "home" :
//doing stuff
break;
case "search" :
//this function will take arguments then perform a query and return results.
$result = $this->search();
//I put $result into a $prod field of my model.
$this->model->prod = $result;
//then I would display acquired data into a table.
echo include 'view/include/result-table.php';
break;
}
}
function search() {
//query DB etc..
}
}
And this is my table (view/include/result-table.php), I would like insert this into a div in my page.
<?php
if (isset ( $this->model->prod )) {
if (count ( $this->model->prod ) == 0) {
echo "<h4 class=\"info\"> No product find";
} else {
?>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Descr</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<?php
foreach ( $this->model->prod as $p ) {
echo "<tr><td> $p->id </td>";
echo "<td>" . ucfirst ( $p->name ) . "</td>";
echo "<td>" . ucfirst ( $p->descr ) . "</td>"
// and so on..
}
?>
</tbody>
</table>
<?php
}
}
?>
Problem 1: the "echo include "view/include/....php" seems to echoes also a 1 (a digit) at the end of the page (or the div). Why?
"Problem 2": This is working pretty well, but I'm not sure that is the correct way to do this. Are there any other solutions to query a DB and display results in a div, with only jquery/ajax request? (I don't want a page refresh every time). Maybe something that can speed up responses and/or improves security.
Thank you very much!
For problem 1: include does not require an echo. Its including the content and the echos are inside the included php file. So the echo include is actualy echoing the result of include, which is true or 1 by success.
problem 2: You are right, ajax would be a solution without refreshing the whole page. All you need to do is to make an ajax request to your php script which returns just the html content you want to replace and append this result to your html dom. jQuery has lots of functions for both making ajax calls and appending the result in your html dom.
A good practice is not to return the raw html content and just append it to your site because if something went wrong you might receive error codes from php or warnings or even mysql errors which is bad to show on your website of course. So in order to tell your ajax request that the result is the expected one just send over a status flag with value true. A good way to do this is by sending the result as json encoded string like this:
{
status : true, //shows you your call was successfull
html : "your result html to place on your site"
}
Only if your ajax call returns the correct status (true) everything went well and you can insert it in your page.
I don't know how to add a comment and keep formatting... anyway:
Thanks for your reply.
I didn't understand the last part, right now I have my ajax call:
$('#submit-btn').click(function(event) {
event.preventDefault();
$.get("index.php", {action : "search" , data : mydata }).done(function(data) {
$('#result').html(data);
});
Removing echo the 1 disappeared, but I don't understand the flag you're talking about and what I should encode. The page I want to append? Only the result of query?
After querying DB, I update my model with new values (coming from db) and then I want to show updated table, in this way will I see the modified table?
I hope my question is clear... :)
Thanks a lot!

Calling multiple functions from the same PHP resource

On my page I'm trying to run two functions from the same .PHP document, however I was getting the error "function already declared".
I had a look here: PHP: how to avoid redeclaring functions?
After looking at this I changed my code to:
<?php
include_once('resource/buildtalentpage.php');
while($row = mysqli_fetch_array($result2)) {
echo getTalentDetails($row);
}
?>
/////////// Loads of HTML ///////////
<?php
include_once('resource/buildtalentpage.php');
while($row = mysqli_fetch_array($result2)) {
echo getTalent($row);
}
?>
The good news is, I don't get the error any more. The bad news is, that function 'getTalent' no longer seems to be called?
The result set from mysql doesn't get reset so your second loop condition returns false the first time through, hence the code never gets called. The easiest thing to do here is do all of your work in one loop.
<?php
include_once('resource/buildtalentpage.php');
$talentHtml = "";
while($row = mysqli_fetch_array($result2)) {
echo getTalentDetails($row);
$talentHtml.= getTalent($row);
}
?>
/////////// Loads of HTML ///////////
<?php
echo $talentHtml;
You should include the file that defines your function one time only. You can then call the function as many times as needed

Jquery - change font color based on value of sql result

I'm looking to change the font color of a div using jquery where the div is populated by the output of a SQL query.
I have:
$(document).ready(function(){
$('#foo').each(function(){
if ($(this).text() == 'bar') {
$(this).css('color','orange');
}
});
});
From a SO search which works fine when the div contains text.
But as this is SQL i'm populating the div with: ".$row['result']."
And this now does not work. I'm guessing this is because the sql, although being a varchar field is a $variable and isn't 'text' as such?.
I'm sure this is something simple, but i'm struggling to phrase this in google to return anything useful.
Many thanks.
edit
The whole thing is rather long and before i've tried to add the jquery was all working fine, so i'll just post the additions.
This is within the head:
echo "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js'></script>";
echo "<script type='text/javascript'>";
echo "$(document).ready(function(){ $('#foo').each(function(){ if ($(this).text() == 'bar') { $(this).css('color','orange');}});});";
Then i echo each row in a while loop:
$sql = "SELECT...";
$result = mysql_query($sql)or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "<div id='foo'>".$row['result']."</div>";
}
The whole document is wrapped in PHP but its not the source of the issue as if i change the div to contain text rather than ".$row['result']." then the jquery executes on it just fine.
You are giving every div the same id ("foo"). An id has to be unique in HTML, you would be better off using a class for this. The way you have it now the .each() function would only be called on one element, possibly the first.
Change the HTML output like this:
echo "<div class='foo'>".$row['result']."</div>";
Then, adapt your selector in jQuery accordingly:
$('.foo').each(function(){
// ...
}
Do you use a $.ajax call or just emmbed the value via PHP on page load?
If you use PHP to print the value, I guess you forgott to echo the value:
".<?php echo $row['result']?>."
Not just:
".$row['result']."

Display personal messages list

I have a personal message system in my website done simply with php/sql. Actually I am facing the trouble to display them using jquery. The db has as fields: message_id, message_from, message_to, message_topic, message_subject and message_status. The way I am showing the message_topic is repeating eight times the following:
echo '<table><tr><td>';
retrieve_msg_topic($result);
echo '</td></tr>'; //of course I won't make 8 tables!!!
the function called is:
function retrieve_msg_topic($result)
{
if($row = mysql_fetch_assoc($result))
{
echo $row['usernombre'];
$message_topic = stripslashes($row['message_topic']);
echo '<div id="msg'.$row['message_id'].'">';
echo $message_topic;
echo '</div>';
//this will return: <div id="msgN">message topic (title, commonly subject)</div>
}
} //end function retrieve msg topic
So far I have a list on a table with the last eight messages sent to the user. The following row is reserved for pagination (next/prior page) and, after that, another row showing the message I select from the list presented, like we see in Outlook. Here is my headache. My approach is to call another function (8 times) and have all of them hidden until I click on one of the messages, like this:
echo '<tr><td>';
retrieve_msg_content($result);
retrieve_msg_content($result); //repeat 8 times
echo '</td></tr></table>';
the function this time would be something like this:
function retrieve_msg_content($result)
{
if($row = mysql_fetch_assoc($result))
{
echo '<script type="text/javascript">
$(document).ready(function(){
$("#msg'.$row['message_id'].'").click(function(){
    $(".msgs").hide(1000);
$("#'.$row['message_id'].'").show(1000);
});
});
</script>';
echo '<div class="msgs" id="'.$row['message_id'].'" style="display: none">'
.$row['message_subject'].
'</div>';
}
/* This function returns:
// <script type="text/javascript">
// $(document).ready(function(){
// $("#msgN").click(function(){
// $(".msgs").hide(1000);
// $("#N").show(1000);
// });
// });
// </script>
// <div class="msgs" id="N" style="display: none">Message subject (body of message)</div>
*/
} //end function retrieve msg content/subject
I could simply explain that the problem is that it doesn't work and it is because I do if($row = mysql_fetch_assoc($result)) twice, so for the second time it doesn't have any more values!
The other approach I had was to call both the message_topic and message_subject in the same function but I end up with a sort of accordion which is not what I want.
I hope I was clear enough.
The easiest way to fix your troubles would be to copy the results of the MySQL query into an array
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
And then use that to build your tables.
edit: What I meant was more along the lines of this:
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
echo '<table>';
foreach($yourArray as $i) {
retrieve_msg_topic($i);
}
echo '<tr><td>';
foreach($yourArray as $i) {
retrieve_msg_content($i);
}
echo '</tr></td></table>';
And then removing everything to do with the SQL query from those functions, like this:
function retrieve_msg_topic($result) {
echo '<tr></td>'$result['usernombre'];
echo '<div id="msg'.$result['message_id'].'">';
echo stripslashes($result['message_topic']);
echo '</div><td></tr>';
}
Right now you're doing some weird key mojo with ret[0] being the topic and $ret[1] being the message, which isn't a good practise. Also, I don't see the declaration of $i anywhere in that code.
The error suggests that the result is empty or the query is malformed. I can't be sure from the code I've seen.
A few other notes: it seems weird that you're using stripslashes() on data that's directly from the DB. Are you sure you're not escaping stuff twice when inserting content into the DB?
Always use loops instead of writing something out x times (like the 8 times you said in your question). Think of a situation where you have to change something about the function call (the name, the parameters, whatever). With loops you have to edit 1 place. Without, you need to edit 8 different places.
BTW, another solution to this problem would be using AJAX to load content into the last cell. If you're curious, I could show you how.
more edits:
For AJAX, build your message list as usual and leave the target td empty. Then, add a jQuery AJAX call:
$('MSG_LIST_ELEMENT').click(function() {
var msgId = $(this).attr('id').replace('msg','');
$.get(AJAX_URL+'?msgID='+msgId,function(data) {
$('TARGET_TD').html(data);
})
});
Replace the capitalized variables with the ones you need. As for the PHP, just echo out the contents of the message with the ID $_GET['msgID'].
However, make sure you authenticate the user before echoing out any messages, so that someone else can't read someone's messages by switching the id number. Not sure how authentication works on your site, but this can be done by using session variables.

Categories