I've took over a PHP app which code is quite a mess so before making any major changes I've decided to rewrite it to MVC (CodeIgniter). As for pure html sections I use $this->load->view(file); technique, but I'm not sure how to cope with something like this:
echo "<tr>";
echo "<td class=\"border szczegolyTd\">";
echo "Kamp.: ".$kampania[$kamp]['idProject'];
echo "<br />";
echo "<b>".$kampania[$kamp]['name']."</b><br />";
echo "<div class='szczegolyDiv'><a class=\"pokaz szczegoly\" href=\"?pokaz=".$kampania[$kamp]['idProject']."\">";
echo "SZCZEGÓŁY";
echo "</a></div>";
if (isset($kampania[$kamp]['timestamp'][$iloLeftCustomers-1])) echo "<br />Dane od: <br /><b>".$kampania[$kamp]['timestamp'][$iloLeftCustomers-1]."</b>";
echo "<br />do: <br /><b>".$kampania[$kamp]['timestamp'][0]."</b>";
//echo "<br />".$ilOstatnichRozmow;
polacz();
$querySpr = mysql_fetch_assoc(mysql_query("SELECT COUNT(*) AS ile FROM lista WHERE user=".$_SESSION['loginid']." AND kampania=".$kampania[$kamp]['idProject'].""));
rozlacz();
if ($querySpr['ile']==0) {
echo "<div id=\"".$kampania[$kamp]['idProject']."\" class=\"tabDodaj\">DODAJ DO OBSERWOWANYCH</div>";
}else{echo "<div class='komunikatMasz'>Masz tę kampanię na liście.</div>";}
echo "</td>";
I'm a beginner in CodeIgniter (and MVC in general), so I don't know all its features and which to choose. Perhaps it's not possible to seperate these 2 technologies completely - so it's more elegant to mainly use html and escape php scripts with <? ?> or to use php and echo html parts?
You can always write html in the template file and insert php in it to loop or echo.
echo "<tr>";
echo "<td class=\"border szczegolyTd\">";
echo "Kamp.: ".$kampania[$kamp]['idProject'];
echo "<br />";
Could be:
<tr>
<td class="border szczegolyTd">
Kamp.: <?php echo $kampania[$kamp]['idProject']; ?>
<br />
Putting code in those PHP tags wil actually fire the call in place. Mind you, to keep the html clean of bussines code make sure you only use echo, foreach, for or if in it.
In CodeIgniter you could render a view file and insert into a "partial" view and just echo it in the main template using TRUE for the 3rd parameter. This only buffers the output instead if immediatly outputting it.
$data['content'] = $this->load->view('ding/templatefile',$vars,TRUE);
if you are really new, please follow this tutorial its nice && informative.
yes it is possible, the best use is short tag + equal sign <strong><?=$variable?></strong> and it echoes whatever is in $variable, whenever you use foreach() use either
foreach($elements as $element) {
$string = "";
$string .= "new line" . $element->id . "<br>";
$string .= "line 2" . $element->name;
echo $string;
}
or just echo lines as you wish
foreach($elements as $element) {
echo "new line" . $element->id . "<br>";
echo "line 2" . $element->name;
}
but remember, before going in to foreach loop, please check if you have valid $variable to go thru. (empty(), isset(), $variable != FALSE...)
note:
if you need condition while echoing basic text use
<strong><?=(condition) ? 'TRUE' : 'FALSE' ?></strong>
example
<strong><?=(isset($variable)) ? $variable : '' ?></strong>
I would advise you go read up on the flow of how a MVC works, but this should point you in the right direction.
In the controller you instantiate the model of the data like:
$this->load->model("lista");
Then,
$data = $this->lista->getCountList($_SESSION['loginid'], $kampania[$kamp]['idProject']);
where in the lista model you have the function:
getCountLista($loginId, $projectId)
which does this part:
return mysql_fetch_assoc(mysql_query("SELECT COUNT(*) AS ile FROM lista WHERE user=".$loginId." AND kampania=".$projectId.""));
Then you pass the returned data to the view
$this->load->view(file, array("listData" => $data));
and in the view:
$listaData[$kamp]['idProject']
It creates an variable in the view foreach item in the array passed in the view.
I commend you to read documentation about MVC.
Related
If I have a large html markup that gets populated with values from the database and gets echoed containig lots of divs that have classes:
echo "<div>";
echo"<div class='className'> {$_results['value']} </div>";
echo"</div>";
. . .
// large markup incoming
How can I save this in a variable so I can send it back as json ? is it possible to do that ?
This is what I am trying to do:
$html = "echo "<div>";
echo"<div class='className'> {$_results['value']} </div>";
echo"</div>";"
echo json_encode(array('html'=> $html, 'otherValue' => $_results['otehr']);
I just don't know how to save all the html in a variable so I can send it back in an array along with other values that need to be used separately.
Using echo means that you output strings. So, if you don't need to output all strings, then concatenate them into one and assign this final string to a variable, e.g.:
$html = "<div>"
. "<div class='className'>" . $_results['value'] . "</div>"
. "</div>";
echo json_encode(array('html'=> $html, 'otherValue' => $_results['otehr']));
A simple fiddle.
I will give you what I think is a great advice.
Use a template system for this, I will recommend you mustacheJS
It will be a little difficult the first time, but you will gain a better and clear code.
I have an old PHP4 web app in which most of the pages looks like this(some pages has a left menu, some doesn't have a footer):
<?php
echo "<html>";
echo "<head><title>TITLE GOES HERE</title></head";
echo "<body>";
echo "<h2>THIS IS A TITLE</h2>";
// Here i fetch data from DB
echo "<table>";
echo "<tr>";
echo "</tr>";
foreach($rowsFromDB as $row) {
echo "<tr>";
// here i echo some <td> containing $row data
echo "</tr>";
}
echo "</table>";
echo "</body>";
echo "</html>";
?>
This is a simple example, the real ones contains a lot of spaghetti code (i'm italian, i like spaghetti but not in my code) and i'm trying to refactor/redesign it in some way. Rewrite the entire app from scratch (maybe with an MVC framework) is not an option because the app contains a lot of business logic i would like to keep.
My idea (for now) is to wrap the echos inside a renderer class, something like this:
<?php
class PageRenderer {
public static function renderHeader() {
echo "<html>";
echo "<head><title>TITLE GOES HERE</title></head";
echo "<body>";
echo "<h2>THIS IS A TITLE</h2>";
}
public static function renderContent($rowsFromDB) {
echo "<table>";
echo "<tr>";
echo "</tr>";
foreach($rowsFromDB as $row) {
echo "<tr>";
// here i echo some <td> containing $row data
echo "</tr>";
}
echo "</table>";
}
public static function renderFooter() {
echo "</body>";
echo "</html>";
}
}
$renderer=new PageRenderer();
$renderer->renderHeader();
// Fetch data from DB
$renderer->renderResults($rowsFromDB);
$renderer->renderFooter();
?>
The problem with the above solution is that is difficult to extend and maintain. Do you know any design pattern or any technique i could use for a better refactoring/redesign?
Thanks in advice and sorry for my bad english
I'd add a method, maybe call it renderColumn($tdParams = array()) which only has simple job of returning a single td element (as a string):
Initialize an empty string, $td_cell
Append to $td_cell an opening <td> tag, maybe accept an array of attributes and values for said td tag as paramater $tdParams which has been set a default value of an empty array.
Append to $td_cell a closing </td> tag.
return $td_cell
For rendering out your DB Rows, you may (at later point in time) have a query that has more, or less data points - thus will result in needing more or less td cells.
For your renderHeader method, I would add at least 2 parameters: title and maybe for the <h2> as you specified, as I can see that changing frequently.
I'm in the middle of a stuggle here, I successfully return data from a website, but then the hyperlink from the site returns as text instead of a link. I wonder if there is any way that I can return it as a link. Also is it possible to display the information inside the hyperlink?
<div data-role="content">
<div class="content-primary">
<?php
$query = 'http://query.yahooapis.com/v1/public/yql?q=Select%20*%20From%20rss%20where%20url%3D%22http%3A%2F%2Fworldoftanks.com%2Fnews%2Frss%2F%22&diagnostics=true';
$xml = simplexml_load_file($query);
//var_dump($xml);
echo '<h2>World of Tank News</h2>';
//iterate over query result set
$results = $xml->results;
foreach ($results->item as $r){
echo $r->title . "<br />";
echo $r->link . "<br /><br />";
}
?>
</div>
Instead of doing:
echo $r->link . "<br /><br />";
do this:
echo "" . $r->link . "";
May be you should use
foreach ($results->item as $r){
echo "" . $r->title . "<br /><br />";
}
For echoing HTML tags this way, I prefer to use printf():
printf(
'%s'
, htmlentities($r->link)
, htmlentities($r->title)
);
printf() takes a string and echos it after replacing specially-formatted tokens. In the above example, there are two tokens in the string, both of which are represented as %s.
When printf() runs, it replaces each token with a corresponding parameter. In the above example, the first %s is replaced by the result of htmlentities($r->link), and the second %s is replaced by the result of htmlentities($r->title).
The manual page for sprintf() goes into more detail about how the tokens work and has many more examples (sprintf() and printf() are identical except that sprintf() returns the formatted string, while printf() outputs it directly).
I'm trying to echo a js function in HTML string inside PHP echo.
And I can't figure it out :
$MY_JS_FUNCTION = '<script type="text/javascript">item + getLastField2()</script>';
if($row2->type == 'text') {
echo "<li id='item-".$row2->rank."' class='list_item'>";
echo "<textarea rows='2' id='".$row2->single_id."' cols='90' name='field[".$MY_JS_FUNCTION."]' data-kind='text' >".$row2->content."</textarea>";
echo "</li>";
echo '<br />';
}
Any ideas to get this work? I think I have so much quotes in it or something like that...
Any help would be very very appreciated, thanks!
I'd reccommend storing the name in the database as well.
Then you can use $row2->name to insert the right name
Your variable $MY_JS_FUNCTION contains an HTML <script> tag with some (strange) JavaScript code (missing a semi-colon). Based on your code the echo on line 5 results in this HTML:
<textarea ... name='field[<script type="text/javascript">item + getLastField2()</script>]' ... >...</textarea>
This is definitively not valid HTML. And there is your problem...
It appears your intent is to echo that JS so that when the page loads, the JS actually sets the value of the name field for that textarea. If that's the case, a simpler way might be something like this:
$MY_JS_FUNCTION = '<script type="text/javascript">document.getElementById("myTextArea").name = item + getLastField2()</script>';
if($row2->type == 'text') {
echo "<li id='item-".$row2->rank."' class='list_item'>";
echo "<textarea rows='2' id='".$row2->single_id."' cols='90' id='myTextArea' data-kind='text' >".$row2->content."</textarea>";
echo $MY_JS_FUNCTION;
echo "</li>";
echo '<br />';
}
That will produce valid HTML. The JS function will fire once that line is reached and update the "name" value to whatever the result of the function is. Be sure to add the "id" field so that the JS knows which element to target.
All right, this must be an absolutely easy question, and I apologize for that.
I also apologize if I simply failed in finding the right search terms to use to come to an answer on my own. I did try, but my lack of fluency in PHP kind of makes me suck at searching.
I'm looking for a simple way to show each date only once within a foreach loop. I'm looping through data like so:
<?php
echo "<ul>";
foreach($rss_items as $i){
if($i->get_feed()->get_title() == 'Twitter (no # replies)'){
echo "<li>";
echo $i->get_date();
echo "<a href='" .$i->get_link()."'>Twitter</a>";
echo $i->get_title();
echo "</li>";
}
elseif($i->get_feed()->get_title() == 'Pinboard (jpcody)'){
echo "<li>";
echo $i->get_date();
echo "<a href='" .$i->get_link()."'>Pinboard</a>";
echo $i->get_title();
echo "</li>";
}
elseif($i->get_feed()->get_title() == 'Entries at Church Marketing Sucks by Joshua Cody'){
echo "<li>";
echo $i->get_date();
echo "<a href='" .$i->get_link()."'>Church Marketing Sucks</a>";
echo "<a href='" .$i->get_link()."'>" . $i->get_title() . "</a>";
echo $i->get_description();
echo "</li>";
}
elseif($i->get_feed()->get_title() == 'Flickr remove first paragraph'){
echo "<li>";
echo $i->get_date();
echo "<a href='" .$i->get_link()."'>Flickr</a>";
echo "<a href='" .$i->get_link()."'>" . $i->get_title() . "</a>";
echo $i->get_description();
echo "</li>";
}
}
echo "</ul>";
?>
And each item contains the date, so I'm getting the same date multiple times. I'd like to only have each date shown once, a la http://daringfireball.net.
I'm using CodeIgniter and the SimplePie library, so all of the data is being pulled directly instead of being stored in a db. I imagine a way to do it could be including a second if statement to check if the date has already been used, but I don't know how to execute this.
I'm pretty new to PHP, and I'm really looking to learn more than just have a solution given.
Any help you could give would be great!
You need to remember what was the date you used last, and print it only if it differs. You can try something like:
$previous_date = null;
foreach ($rss_items as $item) {
if ($item->get_date() != $previous_date) {
$previous_date = $item->get_date();
echo '<li>' . $previous_date . '</li>';
}
...
}
(And don't forget to HTML-encode the titles and links using htmlspecialchars.)
Do you mean you only want the date to be shown once, before the loop, or once per loop so that it looks like:
Date 1
- item 1
- item 2
- etc...
Date 2
- item 1
- item 2
- etc...
Could you clarify the format? Cause at the moment the date should be shown once for each $i that is valid.