How to divide array in parts (without using multidimensional arrays) with php? - javascript

I need to put content in a jquery slider and for the slider each slide is a <li> element and I have to put a list of products within that slide, but it also must automatically create a new slide when it's full.
Now I've decided that I'm going to put 4 elements in a boundry of 1 slide so after 4 elements, the php loop must create a new slide. How can I do that? It looks somewhat like this:
while($r=mysql_fetch_array($sql)) {
echo "
<li>
$r['title']
<li>";
}
but of course, this code creates a new slide everytime it returns the result, which isn't what I want.

you can try this one
<?php
$count=4;
while($r=mysql_fetch_array($sql)) {
if($count % 4==0)
{
echo "<li>";
}
echo $r['title'];
if($count % 4 ==3)
{
echo "</li>";
}
$count++;
}
?>

Maybe something like this?
$i = 1;
while($r=mysql_fetch_array($sql)) {
if($i%4==0) echo "<li>";
echo $r['title'];
if($i%4==3) echo "</li>";
$i++;
};

Related

change div backgroundcolor with js and php

i am working on my first own website. i try to display which cinema seats are already booked, by turning theire backgroundcolor red. i store the reservations in an sql database. i do get the correct value and i can display it on my website, but still the getById won t work.
This is how i create the divs i want to tune:
<?php
for ($i=0; $i < $saalinfo[2]; $i++) {
echo "<div class='rowsaal'>";
for ($j=0; $j < $saalinfo[3]; $j++) {
$k = $i+1;
echo "<a onclick='JavaScript:removeday($k$j)';>";
echo "<div id='$k$j' class='seat' >";
echo "</div>";
echo "</a>";
}
echo "</div>";
}
?>
This is the way i try to change the background color. I used the exact same js wording in other occasions and it did work so i am guessing my id value is not right:
function getres(){
var date = document.getElementById('labeldate').value;
document.getElementById('showdate').innerHTML = date;
var booked;
booked = "<?php echo $dis; ?>"; //$dis is one value i get back from mysqli_fetch_array in this case its 34
document.getElementById(booked).backgroundColor = "red";
document.getElementById('showdate').innerHTML = document.getElementById('showdate').innerHTML + booked;
}
For clarification: booked shows the correct value which is 34 in this case. In the database itself its saved as a txt value. if i look into the html source code i can see that the value 34 is assigned for booked.
booked = "34";
but the div id is set in the following pattern as it is limitted in the use of '' because they are formed in php
</a><a onclick='JavaScript:removeday(34)';><div id='34' class='seat' ></div></a>
i already had some issues where the use of "" and '' lead to different results. Is this the same case here? and how can i fix the issue? Many thanks in advance.
I have not checked all of your code but there is no "backgroundColor" on the element. You need the style property.
document.getElementById(booked).backgroundColor = "red";
should be
document.getElementById(booked).style.backgroundColor = "red";

PHP session from HTML/Javascript onclick not containing the correct value

I have a PHP pagination menu. Each item form the pagination menu contains an a item.
Pagination script:
if ($page_count >= 1 && $page <= $page_count) {
?><li class="page-item <? if($page == 1){echo "active";} ?>"><? echo '<a onclick="myScript(1)" class="page-link">1</a></li>';
$i = max(2, $page - 2);
if ($i > 2)
{
echo ' ... ';
}
for (; $i < min($page + 2, $page_count); $i++) {
?><li class="page-item <? if($i == $page){echo "active";} ?>"><? echo '<a onclick="myScript('. $i .')" class="page-link">' . $i . '</a></li>';
}
if ($i != $page_count)
{
echo ' ... ';
}
?><li class="page-item <? if($page_count == $page){echo "active";} ?>"><? echo '<a onclick="myScript('. $page_count .')" class="page-link">' . $page_count . '</a></li>';
}
When a user clicks on a list <a> item, I want to get the value of the selected item and create a PHP session, containing this item.
This is the Javascript that should create the session:
function myScript(clicked_id)
{
<? $_SESSION["page"] = "clicked_id"; ?>
alert(<? echo "$_SESSION[page]"; ?>);
}
This is working, and in the Javascript alert I get the correct value of the selected item, for example " 2 " if I clicked the list item where the $i value is "2".
The page should refresh, and then, when I check the page session value, I would expect the value " 2 ". However, this is not the case. The value is actually "clicked_id".
This is the code where I check the session:
$page = 1;
if(!empty($_SESSION["page"])) {
$page = $_SESSION["page"];
if($page == 'clicked_id')
{
$page = 1;
}
}
My question is: why is the session not containing the correct value? In the alert the value is correct, but in my check the session doesn't contain the correct value any more. Any help is very much appreciated!
PHP and JS are not compatible; you may not simply include a PHP function in JS.
PHP gets evaluated server-side and javascript gets evaluated client side.
What you probably want to do is to replace your navigations items by links to redirect the user to the desired page.
To understand how PHP works and the result generated by the server, right click on your page and then "View the source code of the page".

Highlight the active subitem inside item-active in carousel slider php

I am trying to achieve as shown below in the image.
I want to create a image carousel slider in which I have 4 items having 4 slides each.
This images act like a radio button selection I am getting the list from the database, so I want to highlight which radio button is selected by highlighting the slide which comes as selected.
So whenever the carousel loads it should highlight the slide which is selected as radio input
Simple Carousel
Here is the link of it : https://bootsnipp.com/snippets/featured/simple-carousel
Here is my Code :
<div class="carousel-inner">
<?php
$result = '';
foreach ($template_data as $key => $value) {
if ($key == 0) {
$result .= '<div class="item active">';
}
elseif ($key !=0 && ($key % 4 == 0)) {
//to avoid first empty "active"
$result .= "</div>";
$result .= '<div class="item">';
}
$result .= '<div class="col-md-3"><img src="http://placehold.it/250x250" alt="#" title="#"></div>';
}
$result .= '</div>';
echo $result;
?>
</div>
Your basic premise looks good to me, though an example on jsFiddle or the like highlighting the problem would be much better. For future questions, consider that.
Meanwhile, I might consider reorganizing your code such that there is never ambiguity of when you write the opening and closing element tags. If you open a tag, close it. Always:
<?php
$result = '';
foreach ($template_data as $key => $value) {
$cssClass = 'item';
if ( /* Your test to determine 'active'; you currently have $key == 0 */ ) {
$cssClass .= ' active';
}
$result .= "<div class='$cssClass'><div class='col-md-3'><a href='#'><img src='http://placehold.it/250x250' alt='#' title='#'></a></div></div>";
}
echo $result;
?>
The only if-check necessary should be to determine if the item is active. If so, modify it accordingly. Otherwise, the loop is the same for every item. Much easier to write, read, and reason about later.

Wordpress news like event slider

I want do something like that - http://imgur.com/kCgH0Jf
I have only function to show 6 posts, but i don't know how do it with content show like a photo.
function six_images_slider() {
$args = array('numberposts' => 18, 'category' => 22);
$recent_posts = wp_get_recent_posts( $args );
$i = 1;
$output = '<div class="slide">';
foreach ($recent_posts as $post) {
$featured_permalink = get_permalink($post['ID']);
$featured_title = get_the_title($post['ID']);
$featured_date = get_the_time('d.m.Y');
$featured_image_src = wp_get_attachment_url( get_post_thumbnail_id($post['ID'] ) );
if ($i == 1) {
$output .= '<div class="col-6 border-l-r">
<big class="white">30</big>
<br /><span class="font-m cream">SIERPIEŃ</span>
</div>';
}
$output .= '';
if ($i == 6) {
$output .= ' </div>';
$i = 0;
}
$i++;
}
$output .= '</div>';
echo $output;
}
I using slick slider to slide next news and more
This is code to whole page:
<section id="wydarzenia" class="page">
<h2>O nas</h2>
<h1>Na Lato Day & Night</h1>
<p>content hover news</p>
<article>
<?php six_image_slider(); ?>
</article>
</section>
Well the link you shared have taken a very different and efficient route. If you look closely, on pressing the next button, the url changes and it takes a sec to load the new page. This means, its not using an image slider and every post has its own comments and description. I dont think its built on wordpress, but if you want to make something like this wordpress, then its much simpler then you expect.
The wordpress way of doing something like this would be as follows.
You need to create a custom post type, and call it something like gallery. Now every post in that gallery will have content area where you can add the images and details about the images, and it will have comments related to that post. Now you can also create categories inside the gallery, and every post will be linked to a gallery. Now when you view a post it will have a next button which will link to the next post from the same category. This way its much more effecient, managable and much much faster :)

how to load more images from a folder using php jquery ajax

i have multiple folders and all folders contain some images upto 20 images.
in my html page i want to show first 5 images and show click to view more 15
and when the user click that link it will show next 15 images
but till now i can only fetch all the images at a time
here is my code
<?php
$dirname = "img/outlets/".$service_type."/". $outlet_name ."/snaps/";
$images = glob($dirname."*.jpg");
foreach($images as $image)
{
?>
<a href="<?php echo $image ?>" class="imageHover">
<img src="<?php echo $image ?>" class="img-responsive" />
</a>
<?php
}
?>
I am sorry for not being supportive or all but I think you should ask or research about "pagination". What you are asking is a definition of pagination.
Actually you are asking , "How do I implement pagination ?"
http://codular.com/implementing-pagination
http://code.tutsplus.com/tutorials/how-to-paginate-data-with-php--net-2928
and here is some code you can try to implement simple pagination
try {
// Find out how many items are in the table
$total = $dbh->query('
SELECT
COUNT(*)
FROM
table
')->fetchColumn();
// How many items to list per page
$limit = 20;
// How many pages will there be
$pages = ceil($total / $limit);
// What page are we currently on?
$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default' => 1,
'min_range' => 1,
),
)));
// Calculate the offset for the query
$offset = ($page - 1) * $limit;
// Some information to display to the user
$start = $offset + 1;
$end = min(($offset + $limit), $total);
// The "back" link
$prevlink = ($page > 1) ? '« ‹' : '<span class="disabled">«</span> <span class="disabled">‹</span>';
// The "forward" link
$nextlink = ($page < $pages) ? '› »' : '<span class="disabled">›</span> <span class="disabled">»</span>';
// Display the paging information
echo '<div id="paging"><p>', $prevlink, ' Page ', $page, ' of ', $pages, ' pages, displaying ', $start, '-', $end, ' of ', $total, ' results ', $nextlink, ' </p></div>';
// Prepare the paged query
$stmt = $dbh->prepare('
SELECT
*
FROM
table
ORDER BY
name
LIMIT
:limit
OFFSET
:offset
');
// Bind the query params
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
// Do we have any results?
if ($stmt->rowCount() > 0) {
// Define how we want to fetch the results
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt);
// Display the results
foreach ($iterator as $row) {
echo '<p>', $row['name'], '</p>';
}
} else {
echo '<p>No results could be displayed.</p>';
}
} catch (Exception $e) {
echo '<p>', $e->getMessage(), '</p>';
}
Simple PHP Pagination script
If I understood you correctly, you want your first page to display 5 images. Then, after clicking on a link, you want the same page to show the remaining images (from 5 up until the number of images in the folder – maybe 20 in your case).
I've been a bit verbose just so that it's clear. I've also left you echoing file paths as your code specifies, but presumably you're going to want to turn these into URLs. I'll leave that to you.
Try something like this:
<?php
$dirname = "img/outlets/".$service_type."/". $outlet_name ."/snaps/";
$images = glob($dirname."*.jpg");
$initial_images = 5; // However many you want to display on the inital load
// Get the starting image and the end image array keys
if($_GET['show_all_images']){ // Check the the browser sent a query parameter
// We've been asked to display more
// Get the array index of the first image. Remember that arrays start at 0, so subtract 1
$first_image_index = $initial_images - 1;
// Get the array index of the last image
$last_image_index = count($images);
}
else{
// We're on the inital load
$first_image_index = 0;
$last_image_index = $initial_images - 1;
}
// Iterate the glob using for. We want to specify an array key, so it's easier here to use for rather than foreach (which is the right solution most of the time)
for ($i=$first_image_index; $i < $last_image_index; $i++):?>
<a href="<?php echo $images[$i] ?>" class="imageHover">
<img src="<?php echo $images[$i] ?>" class="img-responsive" />
</a>
<?php endfor;?>
<?php if($_GET['show_all_images']): // Display a 'show less' link?>
Show less
<?php else: ?>
Show more
<?php endif; ?>
A simple way is to name images to end with indexed. Example being img_1.
You can then use ajax to fetch the last 15 images when user clicks on view more.
But this approach is very basic and is not scalable. As other answers suggest you can mix pagination with indexed image name approach

Categories

Resources