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.
Related
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; ?>
So, I have this special page template in WordPress. I want to use it to display a handful of posts by ID (which I will specify).
Something like
<?php displayPost(10); ?>
and it will have the posts thumbnail, title and some values from the post meta which I will use.
After searching and sweating for hours, this is what I have
<?php
class episodeDetails
{
public $id;
function episodeTitle(){
$title = get_the_title($this->id);
$mykey_values = get_post_custom_values( 'episode', $this->id);
foreach ( $mykey_values as $key => $value ) {
return $title." : ".value;
}
}
function episodeImage(){
return get_the_post_thumbnail_url($this->id);
}
function episodeLink(){
return get_the_permalink($this->id);
}
function episodeMp3(){
$mykey_values = get_post_custom_values( 'enclosure', $this->id);
foreach ( $mykey_values as $key => $value ) {
return strtok($value, "\n");
}
}
}
$episode = new episodeDetails;
$episode->id="480";
?>
<div class="list-videos">
<div class="list-videos-image">
<img width="404" height="404" src="<?php echo $episode->episodeImage(); ?>" class="attachment-portfolio-thumbnail wp-post-image" alt="<?php echo $episode->episodeTitle(); ?>">
</div>
<div class="list-videos-text">
<?php echo $episode->episodeTitle(); ?><br><a class="button" href="<?php echo $episode->episodeLink(); ?>" rel="bookmark"><i class="fas fa-play"></i> Play Now</a> <a class="button" href="<?php echo $episode->episodeMp3(); ?>" download=""><i class="fas fa-download"></i> Download MP3</a>
</div>
</div>
Now, it does display what I want but I feel that it can be done in a better and easier way. My way would require me to copy and paste the whole block of HTML again and again for every additional post. I want to simplify it and I am looking whether there is a concise way instead of my long and complicated HTML part which I feel is recursive.
Thank you
To strictly answer your question: just use a foreach loop.
// Your class declaration to be put here...
// Then declare your IDs
$episodeIds = array(480, 481, 482, ...);
// And finally loop over them
foreach($episodeIds as $id) {
$episode = new episodeDetails;
$episode->id=$id;
?><div class="list-videos">
<div class="list-videos-image">
<img width="404" height="404" src="<?php echo $episode->episodeImage(); ?>" class="attachment-portfolio-thumbnail wp-post-image" alt="<?php echo $episode->episodeTitle(); ?>">
</div>
<div class="list-videos-text">
<?php echo $episode->episodeTitle(); ?><br><a class="button" href="<?php echo $episode->episodeLink(); ?>" rel="bookmark"><i class="fas fa-play"></i> Play Now</a> <a class="button" href="<?php echo $episode->episodeMp3(); ?>" download=""><i class="fas fa-download"></i> Download MP3</a>
</div>
</div><?php
}
Or you can wrap the template part of the code in a function (like your example displayPost(...)) and then call that function within the loop.
// Your class declaration to be put here...
// The display method gets the $episode object as parameter
function displayPost($episode) {
?><div class="list-videos">
<div class="list-videos-image">
<img width="404" height="404" src="<?php echo $episode->episodeImage(); ?>" class="attachment-portfolio-thumbnail wp-post-image" alt="<?php echo $episode->episodeTitle(); ?>">
</div>
<div class="list-videos-text">
<?php echo $episode->episodeTitle(); ?><br><a class="button" href="<?php echo $episode->episodeLink(); ?>" rel="bookmark"><i class="fas fa-play"></i> Play Now</a> <a class="button" href="<?php echo $episode->episodeMp3(); ?>" download=""><i class="fas fa-download"></i> Download MP3</a>
</div>
</div><?php
}
// Then declare your IDs
$episodeIds = array(480, 481, 482, ...);
// And finally loop over them
foreach($episodeIds as $id) {
$episode = new episodeDetails;
$episode->id=$id;
displayPost($episode);
}
I'm working on a carousel in which each images will come from my PHP database. However, each slide just show the same thing. Not sure what loop to include since there is already a 'while' statement.
My database structure is this.
The table name is 'items'
column 1 - id
column 2 - name
column 3 - image
What I'm trying to achieve is for every slide to show the 'image' of every 'id.
Example:
id #1 - potato.jpg
id #2 - tomtato.jpg
and so on...
The code is below.
function display_carousel(){
global $conn;
echo "<div id='myCarousel' class='carousel slide' data-ride='carousel'>
<ol class='carousel-indicators'>
<li data-target='#myCarousel' data-slide-to='0' class='active'></li>
<li data-target='#myCarousel' data-slide-to='1' class='active'></li>
</ol>
<div class='carousel-inner' role='listbox'>";
$sql = "SELECT image FROM items";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result)){
extract($row);
echo "<div class='item active'>
<img src='$image' alt='Image'>
<div class='carousel-caption'>
<h3>CAPTION</h3>
</div>
</div>
<div class='item'>
<img src='$image' alt='Image'>
<div class='carousel-caption'>
<h3>CAPTION</h3>
</div>
</div>";
}
echo "</div>";
echo "<a class='left carousel-control' href='#myCarousel' role='button' data-slide='prev'>
<span class='glyphicon glyphicon-chevron-left' aria-hidden='true'></span>
<span class='sr-only'>Previous</span>
</a>
<a class='right carousel-control' href='#myCarousel' role='button' data-slide='next'>
<span class='glyphicon glyphicon-chevron-right' aria-hidden='true'></span>
<span class='sr-only'>Next</span>
</a>
</div>";
}
The first thing I would do is to make sure what you are getting out of your database is what you think it is by using a var_dump(). Just make sure you are not getting three of the same images from there.
echo '<pre>';
var_dump($result);
echo '</pre>';
Well im having this problem and cant resolved it would like to have some help from you guys, so here it is:
I have this code:
<?php if (mysql_num_rows($tournaments) !=0){
do { ?>
<div id="mainContainer">
<div id="leftContainer">
<img src="images/tournaments/<?php echo $row_tournaments['logo']; ?>.png">
</div>
<div id="rightContainer">
<div id="rightContent">
<p><?php echo $row_tournaments['description']; ?></p>
<a href="tournaments.php?id_tournament=<?php echo $row_tournaments['id_tournament']; ?>">
<div id="galleryButton">
<p>Entrar no torneio</p>
</div>
</a>
</div>
<div id="rightDetails">
<i class="fa fa-gamepad"></i>
<a href="games.php?id_game=<?php echo $row_tournaments['id_game']; ?>">
<?php echo $row_tournaments['game']; ?>
</a>
<br>
<i class="fa fa-calendar-o"></i>
<a href="#">
<?php echo $row_tournaments['date']; ?>
</a>
<br>
<i class="fa fa-pencil-square-o"></i>
<a href="tournaments.php?id_tournament=<?php echo $row_tournaments['id_tournament']; ?>#disqus_thread">
Sem comentários
</a>
<br>
<script type="text/javascript">
function giveThatInputAValue(){
var elem = document.getElementById("search");
elem.value = "<?php echo $row_tournaments['city']; ?>";
/*document.forms["form"].submit();
*/}
</script>
<i class="fa fa-map-marker"></i>
<a onClick="giveThatInputAValue()">
<?php echo $row_tournaments['city']; ?>
</a>
<br>
<img src="images/<?php echo $row_tournaments['online']; ?>.png">
<a href="#">
<?php echo $row_tournaments['online']; ?>
</a>
</div>
</div>
</div>
<?php } while ($row_tournaments = mysql_fetch_assoc($tournaments));
} else {
?>
<div id="noresults">
<p>Sem torneios</p>
</div>
<?php } ?>
Everything loop fine but this part is not looping at all:
<script type="text/javascript">
function giveThatInputAValue(){
var elem = document.getElementById("search");
elem.value = "<?php echo $row_tournaments['city']; ?>";
/*document.forms["form"].submit();*/
}
</script>
And dont know why is it, someone please help. Cumps.
You are defining your function in a loop. Over and over again. So when you call your function, which one should it call? Probably all previous ones have been overwritten by the last version.
You should define your function outside of any loop and then call it with the parameters that you have available in the loop.
Apart from that you are also adding elements with ID's in your loop. ID's need to be unique as well so you should use classes or give them a unique ID.
a real php programmer knows this (meaning i am not one). been a while away from php.
ok first as i see it you never get your first row from result set (someone advise here). you are checking to see if you have rowcount then plod about. i reserve the right to be very wrong.
try something like
if ($result) {
while($row = mysql_fetch_array($result)) {
// output $row info
}
}
else {
echo "nada";
}
put your script for the function at the top
don't surround the main div section creations like you are with a loop
I want to iterate foreach loop to get list of Property details but this code shows nothing please anybody tell me what is wrong in my code
I am new to php.
<?php foreach ($this->Property_Model->getProperty() as $property): ?>
<div class='properties'>
<div class='image-holder'><img src='images/properties/1.jpg' class='img-responsive' alt='properties'/>
<?php if (strcmp($property->status, 'new') == 0) {
?>
<div class='status sold'><?php $property->status ?></div>
<?php
} else {
?>
<div class='status new'><?php $property->status ?></div>
<?php } ?>
</div>
<h4><a href='property-detail.php'><?php $property->property_info ?></a></h4>
<p class='price'><?php $property->prize ?></p>
<div class='listing-detail'>
<span data-toggle='tooltip' data-placement='bottom' data-original-title='Bed Room'>5</span>
<span data-toggle='tooltip' data-placement='bottom' data-original-title='Living Room'>2</span>
<span data-toggle='tooltip' data-placement='bottom' data-original-title='Parking'>2</span>
<span data-toggle='tooltip' data-placement='bottom' data-original-title='Kitchen'>1</span>
</div>
<a class='btn btn-primary' href='property-detail.php'>View Details</a>
</div>
<?php endforeach; ?>
your file line of view is incorrect
< php foreach($this->Property_Model->getProperty() as $property): ?>
you forget ? in your php tag
it should be
<?php foreach($this->Property_Model->getProperty() as $property): ?>
and you can call your model in controller not in view