Optimize connection with Facebook - php

I'm using a script PHP to get all posts from a fan page. The code is this:
require_once("../facebook-sdk/src/facebook.php");
$config = array(
'appId' => '#############',
'secret' => '###############################',
'fileUpload' => false
);
$facebook = new Facebook($config);
$facebook->setAccessToken("###################################");
$pageid = "###############";
$pagefeed = $facebook->api("/" . $pageid . "/feed");
$i = 0;
foreach($pagefeed['data'] as $post) {
if ($post['type'] == 'video' || $post['type'] == 'link' || $post['type'] == 'photo') {
// open up an fb-update div
echo "<div class=\"fb-update\">";
// check if post type is a link
if ($post['type'] == 'link') {
echo '<img class="imagem-feed" src="' . $post["picture"] . '">';
$interno = "<p>" . $post['message'] . "</p><p>" . $post['link'] . "</p>";
}
// check if post type is a photo
if ($post['type'] == 'photo') {
$fotoAlta = $facebook->api("/" . $post["object_id"] . "?fields=source");
echo '<img class="imagem-feed" src="' . $fotoAlta["source"] . '">';
//interno
if (empty($post['story']) === false) {
$interno = "<p>" . $post['story'] . "</p>";
} elseif (empty($post['message']) === false) {
$interno = "<p>" . $post['message'] . "</p>";
}
$interno .= "<p>Ver no Facebook →</p>";
}
// check if post type is a video
if ($post['type'] == 'video') {
echo '<iframe class="imagem-feed" width="350" height="263" src="' . str_replace("&autoplay=1","",$post["source"]) . '" frameborder="0" allowfullscreen></iframe>';
//interno
if (empty($post['story']) === false) {
$interno = "<p>" . $post['story'] . "</p>";
} elseif (empty($post['message']) === false) {
$interno = "<p>" . $post['message'] . "</p>";
}
}
echo '<div class="cabecalho-fanpage"><a target="_blank" href="https://www.facebook.com/Angelameza.arquitetura"><img class="img-perfil-fanpage" width="50" height="50" src="http://profile.ak.fbcdn.net/hprofile-ak-ash1/373040_201176906637605_665931623_q.jpg"><h1>' . $post["from"]["name"] . '</h1><p>' . date("d/m/Y", (strtotime($post['created_time']))) . '</p></a></div>';
echo $interno;
echo '<div class="container-interacoes">';
$totalCurtidas = $facebook->api("/" . $post["id"] . "/likes/?summary=true");
$titulo = ($totalCurtidas["summary"]["total_count"] == 0 || $totalCurtidas["summary"]["total_count"] > 1) ? $totalCurtidas["summary"]["total_count"] . " pessoas curtiram isso." : "1 pessoa curtiu isso.";
echo "<span title='$titulo' class='icon-curtidas'>" . $totalCurtidas["summary"]["total_count"] . "</span>";
$compartilhamentos = (isset($post["shares"]["count"])) ? $post["shares"]["count"] : 0;
$titulo = ($compartilhamentos == 0 || $compartilhamentos > 1) ? $compartilhamentos . " pessoas compartilharam isso." : "1 pessoa compartilhou isso.";
echo "<span title='$titulo' class='icon-compartilhamentos'>" . $compartilhamentos . "</span>";
$totalComentarios = $facebook->api("/" . $post["id"] . "/comments/?summary=true");
$titulo = ($totalComentarios["summary"]["total_count"] == 0 || $totalComentarios["summary"]["total_count"] > 1) ? $totalComentarios["summary"]["total_count"] . " pessoas comentaram isso." : "1 pessoa comentou isso.";
echo "<span title='$titulo' class='icon-comentarios'>" . $totalComentarios["summary"]["total_count"] . "</span>";
echo "</div>";
echo "<div style='clear:both'></div></div>"; // close fb-update div
$i++; // add 1 to the counter if our condition for $post['type'] is met
}
} // end the foreach statement
Using this code, the page is very slow (50 seconds to load). I tested any thing for optimize and don't improve. Can someone help me?

You are making calls to graph API inside the for loop, i.e for every post, you are making additional calls. Obviously, this contributes towards your 50 secs. Your best bet is to arrange your code to use batch requests. Here is the documentation for batching calls.
https://developers.facebook.com/docs/graph-api/making-multiple-requests/
Note: You can make upto 50 calls in one go using a batch request.

Related

Function to get the embedded content and links from a Wordpress post (from 1 to all of them)

I am making a custom design which I will use with Wordpress (not a theme).
I created a function to get one, more or all embedded items in a post.
It works with <img>, <audio>, <video>, <iframe> and <a> tags, but it can be easily edited to get any html tag.
I use it in a loop:
if (have_posts()) : while (have_posts()) : the_post();
I tested it breefly for all tags and different amounts of items, and it works properly with all but iframes. You can get all other tags.
The function gets the src attribute and then recreates the whole element as needed, with additonal attributes if needed.
I'll post the whole function below, it is a little long.
So I would like to get the iframe source. I tried many different preg_match ways to get it but it did not work.
It's weird that it works with 'video' when it's either written first or in if part... but no iframes.
Since I am neither wordpress nor php developer, any other remarks - be it the security concerns or me doing something wrong - I would really appreciate to be told.
I would also like to know if I use properly ob_start(); and does it help to make this function easier for the server, if there are many visitors at the same time...
Also if there is a better way to make the arguments for the function...
I will add later a wrapper for each individual item, which is very useful (for example create a menu from posts links), and I hope that someone might find it useful, especially when those iframes get fixed.
This is the function:
// $universal_modifier for img size ('thumbnail') or link target '_blank'
// example: get_the_customized_post_content('link', 'all', 'link-class', '_blank');
// example: get_the_customized_post_content('image', 1, 'image-class', 'custom-thumbnail');
function get_the_customized_post_content($item_type = null, $items_num = null, $item_classes = null, $universal_modifier = null)
{
// PHP automatically flushes open output buffers when it reaches the end of a script
ob_start();
global $post;
$single_img = false;
if ($items_num) {
if ($item_type === 'image') {
if ($items_num === 1 && $universal_modifier) {
$single_img = true;
// this will get the featured image, which allows for getting
// the 'full' img with its sourceset
the_post_thumbnail($universal_modifier, array(
'class' => esc_attr($item_classes),
'alt' => esc_html(get_the_title())
));
} else {
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $item_src);
$additional_attr = '';
$the_html_tag = '<img';
$close_tag = '';
}
} elseif ($item_type === 'audio') {
preg_match_all('/<audio.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->content, $item_src);
$additional_attr = 'preload=none loading=lazy controls';
$the_html_tag = '<audio';
$close_tag = '</audio>';
} elseif ($item_type === 'video') {
preg_match_all('/<iframe.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $item_src);
$additional_attr = 'loading=lazy frameborder=0 allowfullscreen';
$the_html_tag = '<iframe';
$close_tag = '</iframe>';
if (count($item_src[1]) === 0) {
echo 'Getting videos';
preg_match_all('/<video.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $item_src);
$additional_attr = 'preload=metadata loading=lazy controls';
$the_html_tag = '<video';
$close_tag = '</video>';
}
} elseif ($item_type === 'link') {
preg_match_all('/<a.+href=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $item_src);
preg_match_all('/<a.+>([^\'"]+)<\/a>/i', $post->post_content, $anchor_text);
if ($universal_modifier) {
$additional_attr = 'target=' . $universal_modifier;
} else {
$additional_attr = '';
}
$the_html_tag = '<a';
$close_tag = '</a>';
} else {
echo '<p class="' . esc_attr('not-found-info') . '">' . esc_html('Media not found...') . '</p>';
}
}
if ($single_img) {
$display_item = ob_get_clean();
echo $display_item;
} else {
if (count($item_src[1]) === 0) {
echo '<p class="' . esc_attr('not-found-info') . '">' . esc_html('Media not found...') . '</p>';
} else {
$num_of_items = count($item_src[0]);
if ($items_num === 'all') {
$items_total = $num_of_items;
} else {
$items_total = min($num_of_items, $items_num);
// get the smaller number of the two
}
if ($items_total > 0) {
for ($i = 0; $i < $items_total; $i++) {
if ($item_type === 'link') {
$source_type = 'href';
$item_content = $anchor_text;
} else {
$source_type = 'src';
$item_content = '';
}
$the_item = $the_html_tag . ' class="' . esc_attr($item_classes) . '" ' . $source_type . '="' . esc_url($item_src[1][$i]) . '" ' . esc_attr($additional_attr) . '>' . $item_content[1][$i] . $close_tag;
echo $the_item;
};
};
};
}
}
I had to change the function and I think it is better now. It works completely and is easy to use. The function is quite long…
I used var_dump($post->post_content) and saw that there were no iframes in the post content. They get echoed only in the output on the page.
Therefore I used get_media_embedded_in_content() with an appropriate media type to get the desired content, and then preg_match() to get what is needed.
When required only one image per post, the function gets the posts thumbnail 'full' (the post has to have the featured image – there is a plugin for an automatic creation) which returns the image with the sourceset, which makes it responsive. For more images per post it returns the full image size.
I added a wrapper for each individual item, if it's required. It's possible to add classes to it.
It is useful for wrapping images in a <a> tag – it automatically makes the href.
It’s also useful for wrapping links with <li> tags for making menus from the posts links (personally that was one of the most important things for me in this case).
If set link target, it will be used for all links – either links as items or links as wrappers.
Only images can be properly wrapped in <a> tag, others will be wrapped but will not have the href.
If $item_type set to 'video' it will find both <video> and <iframe> tags. It will search for <iframe> first, because it's most likely that everyone will post videos from external sources than self hosted videos.
<video> and <audio> will have controls.
<video> will have preload="metadata", and <audio> preload="none".
<iframe> will have frameborder="0" allowfullscreen.
All except the links will have loading="lazy".
I'm not sure yet if it will work for all of them with wordpress, but it makes no harm... and can be removed later if useless...
As far as I can see, I escaped all html/attribute/url outputs.
The function is called inside the loop, in the category page:
if (have_posts()) : while (have_posts()) : the_post();
get_the_customized_post_content(
$item_type = 'image',
$items_num = 'all',
$item_classes = 'item-image-class class-two',
$item_wrap = 'a',
$item_wrap_classes = 'item-wrap-class one-more-class',
$the_link_target = '_blank'
);
endwhile;
wp_reset_postdata();
endif;
or:
query_posts(array(
'category_name' => 'your-cat-name',
'posts_per_page' => 1
));
if (have_posts()) : while (have_posts()) : the_post();
get_the_customized_post_content(
$item_type = 'audio',
$items_num = 1,
$item_classes = 'item-audio-class',
$item_wrap = 'div',
$item_wrap_classes = 'item-wrap-class classs-two',
$link_target = false
);
endwhile;
wp_reset_postdata();
wp_reset_query();
endif;
$items_num can be 'all' or from 1 to as many as needed - if specified more items than the post has, it will return all the items the post has.
Anything that is not needed, make it false (… $item_wrap = false, …).
Sure there is a better way to write this, to write only those arguments one needs, and leaving out all that are false, but I do not know how to do it.
I would still like to hear the opinions of the wordpress/php developers, especially on the function's performance, and on the coding – I’m sure it can be written better…
Edit:
Improved preg_match_all for links creation.
Added multiple images alt tag.
Also you have to remove:
Featured Image width/height inline attributes
Featured Image Wordpress default classes
// remove Featured Image width/height inline attributes
function remove_img_size_attr($html)
{
$html = preg_replace('/(width|height)="\d+"\s/', "", $html);
return $html;
}
add_filter('post_thumbnail_html', 'remove_img_size_attr', 10);
add_filter('image_send_to_editor', 'remove_img_size_attr', 10);
// remove Featured Image classes
remove_action('begin_fetch_post_thumbnail_html', '_wp_post_thumbnail_class_filter_add');
all in functions.php
OK, the function (place it in functions.php):
function get_the_customized_post_content(
$item_type = null,
$items_num = null,
$item_classes = null,
$item_wrap = null,
$item_wrap_classes = null,
$link_target = null
) {
// PHP automatically flushes open output buffers when it reaches the end of a script
ob_start();
global $post;
$not_found_class = 'media-not-found'; // class for the p tag container for "Nothing found" info
if ($item_type && $items_num) {
if ($item_type === 'video') {
$the_item_media = get_media_embedded_in_content(apply_filters('the_content', get_the_content(), -1), array('video', 'iframe'));
$num_of_items = count($the_item_media);
} elseif ($item_type === 'audio') {
$the_item_media = get_media_embedded_in_content(apply_filters('the_content', get_the_content(), -1), array('audio'));
$num_of_items = count($the_item_media);
} elseif ($item_type === 'image') {
if ($items_num === 1) {
// this will get the featured image, which allows for getting
// the 'full' img with its sourceset
// it's buffered, otherwise it echos automatically
the_post_thumbnail('full', array(
'class' => esc_attr($item_classes),
'alt' => esc_attr(get_the_title())
));
$featured_img = ob_get_clean();
$the_item_url = get_the_post_thumbnail_url(get_the_ID(), 'full');
$num_of_items = 1;
} else {
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $item_src);
$the_item_media = $item_src[1];
$the_item_url = $item_src[1];
$the_title_attr = $item_src[1];
$num_of_items = count($the_item_media);
};
} elseif ($item_type === 'link') {
preg_match_all('/<a.+href=[\'"]([^\'"]+)[\'"].*>([^\'"]+)<\/a>/i', $post->post_content, $link_parts);
$num_of_items = count($link_parts[0]);
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Please enter the item type.') . '</p>';
};
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Please enter the item type and the number of items to return...') . '</p>';
};
if ($num_of_items > 0) {
if ($link_target) {
$link_target_window = 'target=' . esc_attr($link_target);
} else {
$link_target_window = '';
};
if ($items_num === 'all') {
$items_total = $num_of_items;
} else {
$items_total = min($num_of_items, $items_num);
// get the smaller number of the two
};
if ($item_type === 'image') {
if ($items_num === 1) {
if ($item_wrap) {
if ($item_wrap === 'a') {
echo '<a class="' . esc_attr($item_wrap_classes) . '" href="' . esc_url($the_item_url) . '" ' . $link_target_window . '>';
} else {
echo '<' . $item_wrap . ' class="' . esc_attr($item_wrap_classes) . '">';
}
};
echo $featured_img;
if ($item_wrap) {
echo '</' . $item_wrap . '>';
}
} else {
for ($i = 0; $i < $items_total; $i++) {
if ($item_wrap) {
if ($item_wrap === 'a') {
echo '<a class="' . esc_attr($item_wrap_classes) . '" href="' . esc_url($the_item_url[$i]) . '" ' . $link_target_window . '>';
} else {
echo '<' . $item_wrap . ' class="' . esc_attr($item_wrap_classes) . '">';
}
};
$img_src = pathinfo($item_src[1][$i]);
$img_alt_tag = $img_src['filename'];
$fix_filename = array();
$fix_filename[0] = '/-/';
$fix_filename[1] = '/_/';
$fix_filename[2] = '/\s\s+/';
$img_alt_tag = ucwords(preg_replace($fix_filename, ' ', $img_alt_tag));
echo '<img class="' . esc_attr($item_classes) . '" alt="' . esc_attr($img_alt_tag) . '" src="' . esc_url($item_src[1][$i]) . '" loading=' . esc_attr('lazy') . '>';
if ($item_wrap) {
echo '</' . $item_wrap . '>';
}
};
}
} elseif ($item_type === 'link') {
for ($i = 0; $i < $items_total; $i++) {
if ($item_wrap) {
echo '<' . $item_wrap . ' class="' . esc_attr($item_wrap_classes) . '">';
};
echo '<a class="' . esc_attr($item_classes) . '" href="' . esc_url($link_parts[1][$i]) . '" ' . esc_attr($link_target_window) . '>' . esc_html($link_parts[2][$i]) . '</a>';
if ($item_wrap) {
echo '</' . $item_wrap . '>';
};
};
} elseif ($item_type === 'video') {
for ($i = 0; $i < $items_total; $i++) {
preg_match('/<iframe.+src=[\'"]([^\'"]+)[\'"].*>/i', $the_item_media[$i], $item_src);
if ($item_wrap) {
echo '<' . $item_wrap . ' class="' . esc_attr($item_wrap_classes) . '">';
};
if ($item_src[1]) {
echo '<iframe class="' . esc_attr($item_classes) . '" loading="lazy" src="' .
esc_url($item_src[1]) . '" frameborder="0" allowfullscreen></iframe>';
} else {
preg_match('/<video.+src=[\'"]([^\'"]+)[\'"].*>/i', $the_item_media[$i], $item_src);
if ($item_src[1]) {
echo '<video class="' . esc_attr($item_classes) . '" loading="lazy" src="' .
esc_url($item_src[1]) . '" preload="metadata" controls></video>';
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Media not found.') . '</p>';
};
};
if ($item_wrap) {
echo '</' . $item_wrap . '>';
};
};
} elseif ($item_type === 'audio') {
for ($i = 0; $i < $items_total; $i++) {
preg_match('/<audio.+src=[\'"]([^\'"]+)[\'"].*>/i', $the_item_media[$i], $item_src);
if ($item_wrap) {
echo '<' . $item_wrap . ' class="' . esc_attr($item_wrap_classes) . '">';
};
if ($item_src[1]) {
echo '<audio class="' . esc_attr($item_classes) . '" loading="lazy" src="' .
esc_url($item_src[1]) . '" preload="none" controls></audio>';
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Media not found.') . '</p>';
};
if ($item_wrap) {
echo '</' . $item_wrap . '>';
};
};
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Nothing found.') . '</p>';
};
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Media not found.') . '</p>';
};
};

How to add multiple ID in category

How to add in this code multiple ID category.
I have in kategorija_id 5 arrays:
1 - News
2 - Magazine
3 - Kokursi
4 - Grantovi ect..
I whant to display just key 1 and 2
when i add array i just print the first key
$kategorija = Kategorija::model()->findByPk($item->kategorija_**id=1,2**);
Thnx :)
Code update:
<div class="carousel-inner">
<div class="item active">
<ul class="thumbnails">
<?php
$i = 0;
$lastDefault = 0;
foreach ($ids as $itemId) {
$item = InfoPaket::model()->findByPk($itemId);
$kategorija = Kategorija::model()->findByPk($item->kategorija_id);
if ( $i % 3 == 0 && $i > 0 ) {
echo "</ul></div><div class='item'><ul class='thumbnails'>";
}
$imageUrl = $_SERVER['DOCUMENT_ROOT'] . Yii::app()->baseUrl . "/images/infopaket/" . $item->slika;
if ( !file_exists($imageUrl) || empty($item->slika)) {
if ( $lastDefault == 0 ) {
$imagePath = Yii::app()->baseUrl . "/images/infopaket/info_paket.png";
$lastDefault = 1;
} else {
$imagePath = Yii::app()->baseUrl . "/images/infopaket/info_paket_redv2.png";
$lastDefault = 0;
}
} else {
$imagePath = Yii::app()->baseUrl . "/images/infopaket/" . $item->slika;
}
echo "<li class='span3 thmb-elem'>";
echo "<div class='thumbnail right-caption image'>";
echo "<a class='img-link' href='" . Yii::app()->getHomeUrl() . "?r=infoPaket/clanak&id=" . $item->id . "'><img class='img-class' src='$imagePath'></a>";
echo "</div>";
echo "<div class='caption caption-link'>";
echo "<div class='naziv'><img class='arrow-img' src='". Yii::app()->getBaseUrl() . "/themes/shadow_dancer/images/arrow.png'> " . strtoupper($kategorija->naziv) . "</div>";
echo "<p><a class='naslov' href='" . Yii::app()->getHomeUrl() . "?r=infoPaket/clanak&id=" . $item->id . "'><strong>" . $item->naslov . "</strong></a></p>";
echo "</div>";
echo "</li>";
$i++;
}
?>
</ul>
</div>
</div>
I solve this problem adding this line of code
if ($item->kategorija_id==3 || $item->kategorija_id==4 ) {
now code look like this and it works perfect.
<?php
$lastDefault = 0;
foreach ($ids as $itemId) {
$item = InfoPaket::model()->findByPk($itemId);
$kategorija = Kategorija::model()->findByPk($item->kategorija_id);
if ($item->kategorija_id==3 || $item->kategorija_id==4 ) {
echo '<li>';
echo '<img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/infopaket/info_paket.png" />';
echo '<h2>';
echo strtoupper($kategorija->naziv);
echo '</h2>';
echo '<h1>';
echo "<a class='naslov' href='" . Yii::app()->getHomeUrl() . "?r=infoPaket/clanak&id=" . $item->id . "'>";
echo $item->naslov;
echo '</h1>';
echo '</a>';
echo '</li>';
}
}
?>
findByPk() accepts first argument as array too. So you can do
category::model()->findByPk(array('1', '2'));
Also, $item->category_id will return only single entry. If your item has multiple categories, than set up relations to categories and then get categories ID's with
CHtml::listData($item->categoriesRelationName, 'id', 'id');
can use function ($data){return $data->attribtues} too ---------^--- to get all attributes of model

PHP: Undefined offset in for loop

While making a photo gallery I encountered a problem. With every photo I try to show how many comments it has, however if a photo has 0 comments it will give me an 'undefined offset' error. I have no idea what I am doing wrong because it does show that there are 0 comments.
This is the code of what is relevant to the problem:
(The problem occurres in the line: if($reacties[$i]==0){)
if((isset($_GET['vanafFoto'])) AND (intval($_GET['vanafFoto']>=0)) AND (intval($_GET['vanafFoto'] < $countFotos))){
$begin = intval($_GET['vanafFoto']);
if(($begin + $aantalFotos) <= $countFotos){
$eind = ($begin + $aantalFotos);
} // end if
else {
$eind = $countFotos;
} // end else
} // end if
else {
$begin = 0;
$eind = $aantalFotos;
} // end else
$countFotos = count($fotoArray);
// path naar echte foto
} // end else
echo "<table border='0' cellpadding='0' cellspacing='2'><tr><td ><b>" . $pathspatie . "</b> <small>(" . $count . ")</small>
<br><br><center><small>Pictures " . ($begin + 1) . " - " . $eind . "</small></center></td></tr></table>";
if(($begin - $aantalFotos) >= 0){
$navigation = "<a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&vanafFoto=" . ($begin - $aantalFotos) . "'><</a> " . $navigation;
} // end if
if(($begin + $aantalFotos) < $count){
$navigation .= " <a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&vanafFoto=" . ($begin + $aantalFotos) . "'>></a>";
} // end if
echo $navigation . "<br><br>";
echo "</td></tr><tr>";
$fotonr = 1;
for($i=$begin; $i < $eind; $i++){
$thumb = str_replace($path2, $thumbPath, $fotoArray[$i]);
echo "<td align='center'><a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&fotoID=" . $i . "'><img border='0' src='" . $thumb . "' height='100'><br>";
echo "<small>reacties (";
if($reacties[$i]==0){ // error occurres here.
echo "0";
} // end if
else {
echo $reacties[$i];
} // end else
echo ")</small>";
echo "</a></td>";
$fotonr++;
if($fotonr == ($clm + 1)){
echo "</tr>\n<tr>";
$fotonr = 1;
} // end if
} // end for
If anyone can see what the problem is it would be great!
I did not understand you exact goal but maybe it is better to write one more check:
if(!isset($reacties[$i]) || $reacties[$i]==0){
echo "0";
}

directory error in dynamic php background

I am trying to load a seperate image for each div by getting a directory from a database and inline styling
<div class="query">
<?php
if ($type == "category") {
$query = "SELECT * FROM shopItems WHERE category = '" . $_GET['query'] ."'";
$result = mysqli_query($con, $query);
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$i = $i + 1;
$url = '../img/'.$row['imgSRC'];
if ($i % 2 != 0) {
if ($i != 1) {
echo '</div>';
}
echo '<div class="queryRow"><div class="item" style"background:url(' . $url . ') no-repeat; background-size:contain;">' . $row['productName'] . '</div>';
} else {
echo '<div class="item" style"background:url(' . $url . ') no-repeat; background-size:contain;">' . $row['productName'] . '</div>';
}
}
echo "</div>";
?>
</div>
My problem is that when ever the page is loaded the slashes ("/") in the $url variable are replaced with spaces so the browser thinks an invalid url has been giver, how can i fix this?
Try
style = "background:url(' . $url . ') no-repeat; background-size:contain;"
instead of
style"background:url(' . $url . ') no-repeat; background-size:contain;"
echo '<div class="item" style = "background:url(' . $url . ') no-repeat; background-size:contain;">' . $row['productName'] . '</div>';

Pagination for my situation?

I have a pretty complicated script that doesn't fully work with MySQL, it does partially though. Let me try to explain...
The results of my page are purely image names from a specific folder, means I use this function to get my results:
function get_all_images($dir)
{
$dir = opendir($dir);
$dirArray = array();
while($entryName = readdir($dir))
{
if(($entryName != ".") && ($entryName != "..") && ($entryName != ".svn") && ($entryName != ".htaccess"))
{
$dirArray[] = $entryName;
}
}
closedir($dir);
(sizeof($dirArray)) ? arsort($dirArray) : '';
return (is_array($dirArray)) ? $dirArray : '';
}
This is how I basically get results in my page:
<?php
include('includes/header.php');
$images = get_all_images('i');
$url = str_replace('www.', '', generate_site_url());
$flag = false;
$count = 0;
if (empty($images))
{
echo '<h2>There are no uploaded images</h2><br>';
}
foreach ($images as $image)
{
$filename = $image_name = $image;
$image_link = $url . IMAGES_PATH . $filename;
$user_id = fetch_user_id($image_link);
$delete_link = (isset($_POST['delete_link'])) ? $_POST['delete_link'] : '';
$delete_image = (isset($_POST['delete_image'])) ? $_POST['delete_image'] : '';
if ($delete_admin_submit)
{
unlink('./t/' . $delete_image);
unlink('./t/big' . $delete_image);
adminDelete('./i/' . $delete_image, $delete_link);
header('Location: ' . $imgit_action);
exit();
}
echo '<div class="' . ($count++ % 2 ? "odd-color" : "even-color") . '">';
echo '<table>';
echo '<tr><td class="fullwidth"><a class="preview_img" href="' . $image_link . '"><img src="' . $image_link . '" title="Click to enlarge" width="300" class="thumb" /></a></td></tr>';
echo '<tr><td><span class="default">Direct link:</span> ';
echo '<input type="text" readonly="readonly" class="link-area" onmouseover="this.select();" value="' . $image_link . '" />';
echo '<form method="post" action="" onsubmit="return confirmSingleDeletion();" style="display: inline;"> ';
echo '<input type="submit" class="icon_delete" name="delete_link" value="' . $image_link . '" title="Delete this image" />';
echo '<input type="hidden" name="delete_image" value="' . $image_name . '" />';
echo '</form>';
echo '</td></tr>';
echo ($flag) ? '<hr /><br>' : '';
echo '</table>';
if (!empty($user_id))
{
echo '<br><strong class="normal">Uploader ID:</strong> ';
echo '<em class="normal">' . $user_id . '</em><br>';
}
echo '<br>';
$flag = true;
}
?>
<span class="button-sub">« Back to Index</span>
<?php echo '</div>'; ?>
<?php include('includes/footer_alt.php'); ?>
Now I have not ANY simple clue how to start breaking my results into pages. I'm working here with over 12000 results and it takes a lot for the page to load, I need help to break this big result into pages.
Anyone willing to help me? At least give me a clue how to start? I would be really grateful.
Thanks a lot for reading.
Consider your array as you collect up the file names but after you have sorted them:
$imgs = array(
0 => 'image1.jpg',
1 => 'image2.jpg',
2 => 'image3.jpg',
3 => 'image4.jpg',
4 => 'image5.jpg',
5 => 'image6.jpg',
6 => 'image7.jpg',
7 => 'image8.jpg',
);
// create some vars which you can use in your pagination
$perpage = 3 ;
$page=2;
$range_end = ($perpage*$page)-1;
$range_start = ($perpage*($page-1));
$display=range($range_start,$range_end);
// loop through results
foreach($display as $show){
echo $imgs[$show];
}
Does that get you a start?
Thanks for trying to answer me Cups and Umair Khan, but I found the working solution here:
http://tiffanybbrown.com/2008/12/14/simple-pagination-for-arrays-with-php-5/

Categories