php echo html and php code - php

How can you add this line of code in a
<?=$value["content_title"];?><span class="caret"></span>
so eventually you get something like this:
if (1 == 1) {
echo "<a href='/<?=$value["content_url"];?>'
class="dropdown-toggle" data-toggle="dropdown" role="button"
aria-haspopup="true" aria-expanded="true"> <?=$value["content_title"];?>
<span class="caret"></span></a>";
} else {
echo "Nothing to see!"
}
Because you have multiple punctuations it will end the echo to quick..

Format your string properly. Updated string.
if (1 == 1) {
echo "<a href=\"$value[content_url]\"
class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\"
aria-haspopup=\"true\" aria-expanded=\"true\">$value[content_title]
<span class=\"caret\"></span></a>";
} else {
echo "Nothing to see!";
}
Inside double quoted string the php variables don't need to be quoted. Escape quotes by a backslash.

if you want to actually print the PHP-code, you just have to escale your quotes
echo "<?=$value[\"content_title\"];?><span class=\"caret\"></span>";
if instead you want to print the values, you do not need the tags at all, but just have to concatenate the variables.
echo "<a href='/".
$value["content_url"].
"' class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\" aria-expanded=\"true\">".
$value["content_title"].
"<span class=\"caret\"></span></a>";

if you want to print or echo php code than use concatenate
if (1 == 1) {
echo "<a href='".$value["content_url"]."' class='dropdown-toggle' data-toggle='dropdown' role='button'
aria-haspopup='true' aria-expanded='true'> '".$value["content_title"]."' <span class='caret'></span></a>";
} else {
echo "Nothing to see!"
}

You can use print_f() function:
print_f("<a href='%s' class='dropdown-toggle' data-toggle='dropdown' role='button' aria-haspopup='true' aria-expanded='true'><span class='caret'>%s</span></a>",
$value['content_url'],
$value['content_title']
);
or echo string in "string {var}":
echo "
<a href='{$value['content_url']}' class='dropdown-toggle' data-toggle='dropdown' role='button' aria-haspopup='true' aria-expanded='true'><span class='caret'>{$value['content_title']}</span></a>
" ;
or use concritenate operand . 'string 1'.'string 2'
echo '
<span class="caret">'.$value['content_title'].'</span>
' ;
but best way use template for example
index.php
function getContentUrl() {
return $value['content_url'];
}
function getTitle() {
return $value['content_title'];
}
include './template.phtml';
and template.phtml
<a href='<?php echo getContentUrl() ?>'><?php echo getContentTitle() ?></a>

<a href='<?php echo $value["content_url"]; ?>' class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">
<?php echo $value["content_title"]; ?>
<span class="caret"></span>
</a>
try this

Related

Joomla Database values fetch in custom module

I have created a module in Joomla which will fetch the values from Joomla database table and show in a bootstrap HTML carousal. fetching part is working well but whenever I put the PHP code into Html code where I want those fields to display the carousel is not working. any help will be appreciated. below is my full page code (tmpl/dafault.php)
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/afterglowplayer#1.x"></script>
<?php
defined('_JEXEC') or die;
?>
<?php
$db = JFactory::getDBO();
try {
$query = $db->getQuery(true);
$query->select("*")
->from("tkps5_spotlightamsw_spotlight");
$db->setQuery($query);
$row = $db->loadObjectList();
}
catch (exception $e) { echo $e; }
?>
<div class="container" style="margin-top: 50px;">
<div class="row">
<div class="col-md-6">
<h2 class="block-title1">xyz text</h2>
<p class=" "><a class="button subbutton btn btn-border1" href="#">More info</a></p>
</div>
<div class="col-md-6">
<h2 class="block-title1">Spotlight</h2>
<!-- Wrapper for slides -->
<script>
$(document).ready(function() {
//Enable swiping...
$(".carousel-inner").swipe( {
//Generic swipe handler for all directions
swipeLeft:function(event, direction, distance, duration, fingerCount) {
$(this).parent().carousel('prev');
},
swipeRight: function() {
$(this).parent().carousel('next');
},
//Default is 75px, set to 0 for demo so any distance triggers swipe
threshold:0
});
});
</script>
<?php foreach ($row as $row): ?>
<?php
$fetured_spotlight = $row->featured_spotlight;
$name = $row->name;
$modified_date = $row->modified;
if($fetured_spotlight == 1 )
{
echo "<div id='myCarousel' class='carousel slide' data-ride='carousel' data-touch='true'> ";
echo " <div class='carousel-inner'>";
echo substr($modified_date,0 , 10);
echo "<div class='item '>";
echo "<img src='".$row->thumbnailimage."' alt='".$name."'>";
echo "<div class='carousel-caption1'>";
echo "<p><strong>".$name."</strong></p>";
echo "</div>";
echo "</div>";
//echo $row->name;
echo " <a class='left carousel-control' href='#myCarousel' data-slide='prev'>";
echo " <span class='glyphicon glyphicon-chevron-left'></span>";
echo " <span class='sr-only'>Previous</span>";
echo " </a>";
echo " <a class='right carousel-control' href='#myCarousel' data-slide='next'>";
echo " <span class='glyphicon glyphicon-chevron-right'></span>";
echo " <span class='sr-only'>Next</span>";
echo " </a>";
echo "</div>";
}
?>
<?php endforeach; ?>
<!-- Left and right controls
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>-->
<p class="align-right"><a class="button subbutton btn btn-border1" href="flame-spotlight">VIEW ALL</a></p>
</div>
</div>
</div>
</div>
Finally i got the answer where i was not assigning the "active" class to first slider image. so below is my working code .. just posting for loop rest of the code is same..
<?php foreach ($row as $key=>$row): ?>
<?php
$fetured_spotlight = $row->featured_spotlight;
$name = $row->name;
if($fetured_spotlight == 1 )
{
?>
<div class='item <?php echo ($key == 0) ? "active" : ""; ?>'>
<?php
echo "<img src='".$row->thumbnailimage."' alt='".$name."'>";
echo "<div class='carousel-caption1'>";
echo "<p><strong>".$name."</strong></p>";
echo "</div>";
//echo $row->name;
echo "<br />";
}
?>
</div>
<?php endforeach; ?>

Concatenate HTML in controller

I am working on search data, and want to send HTML from controller to view with AJAX. I am getting syntax error. Here is my code.
function search()
{
$params['searchKeys'] = $this->input->post('query');
$params['userID'] = $this->session->userdata('id');
$storeArray = $this->Store_model->searchStore($params);
foreach($storeArray as $store){
echo "<div class='col-lg-3 col-md-4 col-sm-6 col-xs-12'>
<div class='store-block'>
<img class='img-responsive' src=".getImageURL($s['image'], array( 'alt' => '' )).">
<div class='overlay'>
<h2>".$s['storeName']."</h2>".if($this->session->userdata('userType') == '2'):.
.if($s['isBlocked'] == '1'):.
"<a class='info'>Your store is blocked!</a>
".else:."
<a class='info' href=".site_url('Store/preview/'.encode($s['storeID'])).">Preview</a>
<a class='info' href=".site_url('Slot/index/'.encode($s['storeID'])).">Slots</a>
<a class='info' href=".site_url('Booking/index/'.encode($s['storeID'])).">Bookings</a>
<a class='info' href=".site_url('Store/edit/'.encode($s['storeID'])).">Edit</a>
<a class='info' href='#'data-toggle='modal' data-target='#confirm-".$s['storeID'].">Delete</a>
".endif;."
".elseif($this->session->userdata('userType') == '1'):."
<a class='info' href=".site_url('Store/preview/'.encode($s['storeID'])).">Preview</a>
".if($s['isBlocked'] == '0'):.
"<a class='info' href='#' data-toggle='modal' data-target='#confirm-block-".$s['storeID'].">Block</a>
".else:."
<a class='info' href='#' data-toggle='modal' data-target='#confirm-unblock-".$s['storeID'].">Un block</a>
".endif.
.endif."
</div>
</div>
</div>
</div>
";
}
exit;
}
I am getting error on this line.
<h2>".$s['storeName']."</h2>".if($this->session->userdata('userType') == '2'):.
The error is because $s is not defined. You either have to change
foreach($storeArray as $store){
to
foreach($storeArray as $s){
Or change every instance of $s['example_key'] to $store['example_key']
But you are still going to run into the problem described in #Bartek's comment.
This whole thing could be made easier by using $this->load->view which will "echo" the view file for you. Writing HTML that drops into and out of the PHP processor is easier to write and read. Plus it's a lot more versatile.
Here's the controller that loads a view.
public function search()
{
$params['searchKeys'] = $this->input->post('query');
$params['userID'] = $this->session->userdata('id');
$viewdata['storeArray'] = $this->Store_model->searchStore($params);
$this->load->view('store_search_view', $viewdata);
}
The "view": /application/views/store_search_view.php
<?php
foreach ($storeArray as $s) :
$storeID = $s['storeID'];
$enc_storeID = encode($storeID);
?>
<div class='col-lg-3 col-md-4 col-sm-6 col-xs-12'>
<div class='store-block'>
<img class='img-responsive' src=".getImageURL($s['image'], array( 'alt' => '' )).">
<div class='overlay'>
<h2><?php echo $s['storeName']; ?></h2>"
<?php
if($this->session->userdata('userType') == '2'):
if($s['isBlocked'] == '1'):
?>
<a class='info'>Your store is blocked!</a>
<?php
else:
?>
<a class='info' href='<?php echo site_url('Store/preview/'.$enc_storeID); ?>'>Preview</a>
<a class='info' href='<?php echo site_url('Slot/index/'.$enc_storeID); ?>'>Slots</a>
<a class='info' href='<?php echo site_url('Booking/index/'.$enc_storeID); ?>'>Bookings</a>
<a class='info' href='<?php echo site_url('Store/edit/'.$enc_storeID); ?>'>Edit</a>
<a class='info' href='#' data-toggle='modal' data-target='#confirm-<?= $storeID; ?>'>Delete</a>
<?php
endif;
elseif($this->session->userdata('userType') == '1'):
?>
<a class='info' href='<?= site_url('Store/preview/'.$enc_storeID); ?>'>Preview</a>
<?php if($s['isBlocked'] == '0'): ?>
<a class='info' href='#' data-toggle='modal' data-target='#confirm-block-<?= $storeID; ?>'>Block</a>
<?php else: ?>
<a class='info' href='#' data-toggle='modal' data-target='#confirm-unblock-<?= $storeID; ?>'>Un block</a>
<?php
endif;
endif;
?>
</div>
</div>
</div>
<?php
endforeach;
In case you're wondering, it is more efficient to drop into and out of PHP "mode" than to concatenate a gigantic string. There is zero performance penalty for switching between processing PHP and outputting HTML directly.
If you're not familiar with the syntax, <?= ... is the same as <?php echo .... If it seems I was switching between the two syntax styles at random that is true. There's no reason for one style over the other except one involves less typing.
<h2>".$s['storeName']."</h2>".if($this->session->userdata('userType') == '2'):.
The error comes from if() part. You can't use if() inside echo.
Instead you can save result of your if condition to variable and display it in echo or you can put your echo inside the if() else block.

Adding an active class according to URL

I have a php/mysql driven menu. I am trying to add an active class to the menu item whenever the URI reflects that menu item (basically, when I am on that page) but every example I find is with a menu that is not populated through an array or repeater like mine.
How can manipulate the active class you see below so that it shows only when I am on that page?
Here is my menu
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if($row['id'] == 2){
// below is the active class that is now being populated accross all items equally
echo '<li class="nav-item dropdown active">';
echo '<a href="#" class="nav-link dropdown-toggle animated fadeIn animation-delay-7" data-toggle="dropdown" data-hover="dropdown" role="button" aria-haspopup="true" aria-expanded="false" data-name="services">';
echo $row["pagename"];
echo '<i class="zmdi zmdi-chevron-down"></i>';
echo '</a>';
// create a new list
echo '<ul class="dropdown-menu">';
// loop second/submenu query results
while($sub_row = $result2->fetch_assoc()) {
echo '<li>';
echo '' . $sub_row["pagename"] . '';
echo '</li>';
}
echo "</ul>";
echo '</li>';
} else { // for all other menu links
echo '<li class="nav-item dropdown active">';
echo '' . $row["pagename"] . '';
echo '</li>';
}
}
} else {
echo "0 results";
}
?>
The screenshot below shows the result after it renders. Notice the active class highlighted in yellow, it is added to every item in my main menu (the way I have it coded, which it's wrong of course). The green is the $sub_row["link"] (to answer Mark's question below
Notice, the active class is only needed to be added programmatically on the main menu. (the else portion of my code).
The screenshot below shows how the active class affects the menu item if the user was in the www.domain.com/how-it-works.php page. The active class contians the styles to make the menu item appear that way.
Thanks in advance
Hard to test with not having the DB outputs to match against mate but try this, basically you want an if statement to get the current page URL and match it against the url you get back from the DB.
<?php
if ($result->num_rows > 0) {
$pageURL = str_replace('/', '', $_SERVER['REQUEST_URI']);
$homeURL = $_SERVER['REQUEST_URI'];
// output data of each row
while($row = $result->fetch_assoc()) {
if($row['id'] == 2){ ?>
<li class="nav-item dropdown">
<a href="" class="nav-link dropdown-toggle animated fadeIn animation-delay-7" data-toggle="dropdown" data-hover="dropdown" role="button" aria-haspopup="true" aria-expanded="false" data-name="services">
<?php echo $row["pagename"];?>
<i class="zmdi zmdi-chevron-down"></i>
</a>
<ul class="dropdown-menu">
<?php while($sub_row = $result2->fetch_assoc()) {?>
<li>
<a href="<?php echo $sub_row["link"]; ?>" class="dropdown-item">
<?php echo $sub_row["pagename"] ?>
</a>
</li>
<?php } ?>
</ul>
</li>
<?php
} else if($row['id'] == 1){ ?>
<li class="nav-item dropdown <?php echo ($homeURL == $row["link"])? 'active' : '';?>">
<a href="<?php echo $row["link"]; ?>" class="nav-link dropdown-toggle animated fadeIn animation-delay-7">
<?php echo $row["pagename"]; ?>
</a>
</li>
<?php
} else { ?>
<li class="nav-item dropdown <?php echo ($pageURL == $row["link"])? 'active' : '';?>">
<a href="<?php echo $row["link"]; ?>" class="nav-link dropdown-toggle animated fadeIn animation-delay-7">
<?php echo $row["pagename"]; ?>
</a>
</li>
<?php }
}
} else {
echo "0 results";
}
?>
Edit:
Bit that gets the current page url is:
$pageURL = end(explode('/', $_SERVER['REQUEST_URI']));
Bit that does the check is (this is just a shorthand if statement:
<?php echo ($pageURL == $row["link"])? 'active' : '';?>

If Statements in print to loop new <li>

I am looping information from database as $id , $akt and $nmn. I want to make some if-statements in this print if its possible.
I have a counter before my loop $counter = 0; and adding $counter++;
I want to print td with the dropdown once. But i want to print the li as long there is any in database. I think the right way is to it with a counter. But i need some help. Any suggestion?
print("<td class='center'><div class='dropdown'>
<button class='btn btn-primary dropdown-toggle'
type='button' data-toggle='dropdown'> Activities
<span class='caret'></span></button>
<ul class='dropdown-menu'>
<li><a href='#'>$id , $akt , $nmn </a></li>
</ul>
</div>
</td>\n");
print("</tr>\n");
I have many td in this tr.
This is what i wanna do.
if ($counter < 1){
print("<td>>$produktionsgrupp</td>\n");
print("<td>$namn</td>\n");
print("<td>$kvikt</td>\n");
print "<td class='center'> <div class='dropdown'> <button class='btn btn-primary dropdown-toggle'
type='button' data-toggle='dropdown'> $nmn
<span class='caret'></span></button>
<ul class='dropdown-menu'>";
}
print "<li> <a href='#'> $nmn </a> </li>";
if ($counter < 1){
print "</ul> </div> </td>\n";
print("</tr>\n");
}
First print things that you print only once:
print "<td> <div> <ul class='dropdown-menu'>";
Then loop the data you retrieved from your db:
foreach ($data_from_db as $data) {
print "<li> <a href='#'> $data </a> </li>";
}
Then close the elements you've opened before:
print "</ul> </div> </td>";
I'm not sure if this is what you're looking for, your question was not quite clear. Feel free to comment tho, hope it helps!

Resource id #9 showing

So i'm trying to get a list of activities(subjects) of a school and i get them all like it's on the Database but i also gives me Resource id #9 i've tried to remake the code so many times but it gives me every single time this.
1st try
<li>
<?php
if(Session[tipo]<=1){
echo "
<li class='treeview'>
<a href='#'>
<i class='fa fa-share'></i> <span>Atividades</span>
<i class='fa fa-angle-left pull-right'></i>
</a>
<ul class='treeview-menu'>
<li>".
$result = mysql_query("select * from atividade_aluno where ativo=1");
while($row = mysql_fetch_object($result)) {
echo "<a href='lista.php?x=$row->id_atividade'>". utf8_encode($row->atividade)."</a>";
?>
<?php
}
?><?php
echo "
</li>
</ul>
</li>";
}else{
echo "<a href='#'>1</a>";
}
?>
</li>
2nd try
<li>
<?php
if(Session[tipo]<=1){
echo "
<li class='treeview'>
<a href='#'>
<i class='fa fa-share'></i> <span>Atividades</span>
<i class='fa fa-angle-left pull-right'></i>
</a>
<ul class='treeview-menu'>
<li>".
$result = mysql_query("select * from atividade_aluno where ativo=1");
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "<a href='lista.php?x=".$row["id_atividade"]."'>". utf8_encode($row["atividade"])."</a>";
?>
<?php
}
?><?php
echo "
</li>
</ul>
</li>";
}else{
echo "<a href='#'>1</a>";
}
?>
</li>
PS: The result is the same so i won't upload two pictures of the same.
Thanks you so mutch for your time
The . operator concatenates strings in PHP. For example, this prints "helloworld":
$a = "hello";
$b = "world";
echo $a . $b;
Now, in your code you have this:
<li>".
This concatenates to the next variable ($result). You should change it to:
<li>";
Just change your code to this
<li>
<?php
if(Session[tipo]<=1){
$result = mysql_query("select * from atividade_aluno where ativo=1");
echo "
<li class='treeview'>
<a href='#'>
<i class='fa fa-share'></i> <span>Atividades</span>
<i class='fa fa-angle-left pull-right'></i>
</a>
<ul class='treeview-menu'>
<li>".
while($row = mysql_fetch_object($result)) {
echo "<a href='lista.php?x=$row->id_atividade'>". utf8_encode($row->atividade)."</a>";
?>
<?php
}
?><?php
echo "
</li>
</ul>
</li>";
}else{
echo "<a href='#'>1</a>";
}
?>
</li>
You concatenated $result which is resource id with your string. That is the reason.

Categories