PHP sort not working in Chrome and Safari - php

I am not sure if it is the sort that isn't working or the way that I am outputting the information. But it would seem that the order that these "li" elements are being made is wrong sometimes.
The images in the folder are named something like
A-Mike-groomsman-topRight-light.jpg
B-James-groomsman-topRight-light.jpg
C-Jared-groomsman-topRight-light.jpg
Code is below. The "li" are in the right order in Firefox, but Chrome and Safari sometimes they put the last one first. Then sometimes they don't. Though I wonder if it could be the bxslider moving things around after the page load? Anyone experience this before?
<?PHP
$titleName = 'who\'s who'; //Wording for title of this section. Change this if you want to change the title text of this section
include 'modules/title.php';
$boydirectory = $_SERVER['DOCUMENT_ROOT']."/resources/images/who/boys";
$girldirectory = $_SERVER['DOCUMENT_ROOT']."/resources/images/who/girls";
$boy_results_array = array();
$girl_results_array = array();
if (is_dir($boydirectory))
{
if ($handle = opendir($boydirectory))
{
foreach(glob($boydirectory.'/*.*') as $file)
{
$boy_results_array[] = basename($file);
}
closedir($handle);
}
}
if (is_dir($girldirectory))
{
if ($handle = opendir($girldirectory))
{
foreach(glob($girldirectory.'/*.*') as $file)
{
$girl_results_array[] = basename($file);
}
closedir($handle);
}
}
sort($boy_results_array);
sort($girl_results_array);
?>
<div class="whoSlider boy">
<h3>Boys</h3>
<ul class="whoBoysbxslider">
<?php
if(count($boy_results_array) > 0){
for ($i = 0; $i < count($boy_results_array); $i++) {
$result = explode('-', $boy_results_array[$i]);
$name = str_replace("_", " ", $result[1]);
$job = str_replace("_", " ", $result[2]);
$alignment = $result[3];
$color = str_replace(".jpg", "", $result[4]);
echo "<li>";
echo "<img src=\"../resources/images/who/boys/$boy_results_array[$i]\" />";
echo "<div class=\"captionContainer $alignment $color\">";
echo "<span>$name</span>";
echo "<span>$job</span>";
echo "</div></li>";
}
}
?>
</ul>
</div>
<div class="whoSlider girl">
<h3>Girls</h3>
<ul class="whoGirlsbxslider">
<?php
if(count($girl_results_array) > 0){
for ($j = 0; $j < count($girl_results_array); $j++) {
$result = explode('-', $girl_results_array[$j]);
$name = str_replace("_", " ", $result[1]);
$job = str_replace("_", " ", $result[2]);
$alignment = $result[3];
$color = str_replace(".jpg", "", $result[4]);
echo "<li>";
echo "<img src=\"../resources/images/who/girls/$girl_results_array[$j]\" />";
echo "<div class=\"captionContainer $alignment $color\">";
echo "<span>$name</span>";
echo "<span>$job</span>";
echo "</div></li>";
}
}
?>
</ul>
</div>

Apparently the issue was not with php but with the BX slider. The issue is it was going to the clone slide instead of the first slide. Only in chrome and Safari. The below link talks about the issue.
https://github.com/stevenwanderski/bxslider-4/issues/154
The solution in there that worked for me was adding this to the jquery.bxslider.css file
.bx-viewport li { min-height: 1px; min-width: 1px; }

try
flush()
after echo() to make sure the content you want to print is sent to the client at that point.

First of all, PHP is a server side language and the behaviour is not effected by the browser.
So I would say that your issue is caused by bxslider which is a jQuery plugin so the behaviour it could be affected by the browser.
To check that you can press ctrl+u in firefox and chrome and see that the html is the same.

Related

make an image (background-image CSS) into PHP variable value

I want to make a product gallery like 5 products, each has their own background-image attribute
I use loop to insert the product image, so I want to make it each loop will have different background-image
I'm thinking of using IF statement like so
<?php
$bg = 0;
$bg1 = "url('img1.jpg')";
$bg2 = "url('img2.jpg')";
$bg3 = "url('img3.jpg')";
$bg4 = "url('img4.jpg')";
$bg5 = "url('img5.jpg')";
if ($bg = 0){
echo " <div style='background-image :$bg1 ;'>" ;
$bg = 1;
} else if ($bg= 1) {
echo " <div style='background-image :$bg2 ;'>" ;
$bg = 2;
} else if ($bg= 2 ) {
echo " <div style='background-image :$bg3 ;'>" ;
$bg = 3;
} else if ($bg= 3 ) {
echo " <div style='background-image :$bg4 ;'>" ;
$bg = 4;
} else if ($bg= 4 ) {
echo " <div style='background-image :$bg5 ;'>" ;
$bg = 0;
}
echo " </div> " ;
code for product images
?>
above is the simplified code I wrote, it doesn't work.
if anyone has a different but much simpler solution it will be appreciated
note : the image files are in the same directory with this php file
thank you
Would you be open to using img tags? This, in my opinion, would be a better solution:
Code:
<?php
$images=Array(
"img1.jpg",
"img2.jpg",
"img3.jpg",
"img4.jpg",
"img5.jpg"
);
//
print "\n<br> Code: \n<pre>\n".RenderThoseImages($images)."\n</pre>";
//
function RenderThoseImages($images)
{
//
$s="";
//
foreach($images as $image){
$s.="\n<div><img src=\"{$image}\"></div>";
}
return $s;
}
?>
Outputs:
<br> Code:
<pre>
<div><img src="img1.jpg"></div>
<div><img src="img2.jpg"></div>
<div><img src="img3.jpg"></div>
<div><img src="img4.jpg"></div>
<div><img src="img5.jpg"></div>
</pre>
The main reason being that when you use the background-image CSS, you're also responsible for grabbing the image dimensions in PHP and rendering height/width into the div CSS as well, or possibly creating some javascript to fix it after loading, creating unneeded headache.

Separate MySQL results into Divs using while loop

Just beginning PHP to bear with me.
Results I'm trying to achiever:
I have a table of YouTube URL's and MetaData.
Trying to build this:
<div class="slide">
<iframe></iframe>
<iframe></iframe>
</div>
<div class="slide">
<iframe></iframe>
<iframe></iframe>
</div>
Two videos per slide, then I'm going to paginate through results using Deck.js.
I suspect I'm going about this completely the wrong way, not that experienced at programmin g logic;
while($data = mysql_fetch_array($result)) {
for ($counter = 1; $counter<=2; $counter++) {
echo "<div class=\"slide\">";
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
/* If Video 1, increment counter for 2nd video */
if ($counter == 1) {
$counter++;
}
/* If Video 2, close div and reset counter */
else if ($counter == 2) {
echo "</div>";
$counter = 1;
}
/* If error break out */
else {
echo "</div>";
break;
}
}
}
Basically trying to nest loops to keep track of how many videos per div and start a new one when a div has two.
I've tried a few different ways, this being the latest. Results in:
<div class="slide">
<iframe></iframe>
<div class="slide>
<iframe></iframe>
Hit the blank wall now, not sure what to try next. Willing to use/learn any method to accomplish the results, just not sure where to go at this point.
Cheers.
You could remove the second loop all together using the % operator (modulus). The idea is that a % b === 0 then the number a was evenly divisible by b. Using this, you can easily check for even or odd or every Nth row.
$k = 1;
echo "<div class=\"slide\">";
while($data = mysql_fetch_array($result)) { // you should really change to mysqli or PDO
if($k % 3 === 0){
echo "</div>";
echo "<div class=\"slide\">";
}
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
$k++;
}
echo "</div>";
Put the echo <div> before the for loop (still inside the while loop) and the </div> after the for loop
In your while loop you're retrieving just one row, but then you're iterating over it twice with a nested loop. Do away with the inner loop and just use a flip-flop variable to track left and right. I think this will do what you want:
$left=true; // track whether we're emitting HTML for left or right video
while($data = mysql_fetch_array($result)) {
if ($left) {
echo "<div class=\"slide\">";
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
}
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
if (!$left) {
echo "</div>";
}
$left = !$left; // invert $left to indicate we're emitting the right iFrame
}
// end of loop. If we had an odd number of
// videos, tidy up the HTML
if (!$left) {
echo "</div>";
}
PHPFiddle
<?php
$x = 10;
$counter = 0;
while($x > 0)
{
if($counter != 0 && $counter % 2 == 0)
{
echo "ENDOFSLIDE</br>";
}
if($counter == 0 || $counter % 2 == 0)
{
echo "SLIDE</br>";
}
echo "iframe => $x </br>";
$x--;
$counter++;
}
echo "ENDOFSLIDE";
?>
It won't work because the for loop is inside the fetch loop for the SQL data. The second iteration of the for loop does not have a new SQL row. A better solution would be to capture the common column that identifies the two videos (the title) and generate a new div whenever that value changes. Try something like this, which will work for any number of SQL rows with the same title. This will also give proper results if the SQL query returns no rows and will handle the potential of a title with only one URL - which could get ugly if you merely flip-flop and end up with URLs on the wrong title. Of course, as in your current solution, your SQL query must ORDER BY VIDEO_TITLE so the rows are adjacent. I didn't run it, but should be close.
$lastTitle = "";
$n = 0; //count SQL rows processed
while($data = mysql_fetch_array($result)) {
// See if the title changed from last
if( $data['VIDEO_TITLE'] != $lastTitle ) {
// if we processed any rows, must end the current div before starting a new one
if( $n > 0 )
echo "</div>";
echo "<div class=\"slide\">";
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
//save the title as last title
$lastTitle = $data['VIDEO_TITLE'];
}
$n++; //count the SQL row
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
}
if( $n > 0 )
echo "</div>";

limit the word count and add a read more link

Ok i have this code so far which is in my wordpress template so precisely this a wordpress stuff.
<?php
$post_id = 266;
echo "<div id='widgets-wrapper3'><div id='marginwidgets' style='overflow: auto; max-width: 100%; margin: 0 auto; border: none !important;'>";
$queried_post = get_post($post_id);
echo "<div class='thewidgets'>";
echo $queried_post->post_content;
echo '</div>';
echo "</div></div>";
?>
as you can see into the code, the routine is, to display the post which has an id of 266, now all i want is to limit the word count in the post content of that post, let say I want to limit the word to 300 and then add a read more link. how to make that please?
hope there's someone here who figured out how to make that.
I am open in, Ideas, recommendation and suggestion. Hope someone here could help, thank you.
try this:
http://codex.wordpress.org/Function_Reference/the_excerpt
or use php substr:
echo get_sub($queried_post->post_content, 300);
function get_sub($str, $max=300)
{
$ar = explode($str);
$count = 0;
$new_str = "";
$del = " ";
foreach($ar as $a)
{
if($count == 0)
{
//no space
$del = "";
}
if($count < $max)
{
$new_str .= $del.$a;
}
$count++;
}
return $new_str;
}
if the content contains html elements, its a problem.
hope it helps

Jquery/ Javascript getting information from PHP scope issue?

I am trying to get some information from our database and then use it in javascript/JQuery and I think I might be doing something wrong with the scope of the coding.
Here is the current segment of code on my phtml page (magento)
<script type="text/javascript">
<?php
echo 'var $image-paths = new Array();';
for ($i = 0; $i < count ($_child_products); $i++)
{
echo '$image-paths[';
echo $i;
echo '] = ';
echo $this->helper('catalog/image')->init($_child_products[$i], 'image');
echo ';';
}
?>
document.getElementById('main-image').href = $image-paths[1];
</script>
The bottom getElementById is just for testing to see if it really grabbed that image path. So far the php stuff is working and echo'ing the correct links. However, is simply echo'ing them not enough; does it actually register it into the javascript code?
Here is what my source code looks like on my server:
<script type="text/javascript">
var $image-paths = new Array();
$image-paths[0] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5f b8d27136e95/feeds/MrsMeyers/MRM-64565-a.jpg;
$image-paths[1] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-64566-a.jpg;
$image-paths[2] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-64568-a.jpg;
$image-paths[3] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-D43114-a.jpg;
document.getElementById('main-image').href = $image-paths[1];
</script>
But the image link does not change to image-path[1]. Any ideas?
Thanks in advance!
$image-paths[0] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5f b8d27136e95/feeds/MrsMeyers/MRM-64565-a.jpg;
^-- no quote here, or at the end of the string
You're producing invalid javascript. Pop up your javascript console (shift-ctrl-J in chrome/firefox) and you'll see the error.
Producing javascript dynamically is problematic. Anytime you insert something from a PHP variable/function, you should run that through json_encode(), which guarantees you get valid javascript:
echo json_encode($this->helper('catalog/image')->init($_child_products[$i], 'image'));
Or better yet, change the code to:
$links = array();
for ($i = 0; $i < count ($_child_products); $i++)
$links[] = $this->helper('catalog/image')->init($_child_products[$i], 'image');
}
echo '$image-paths = ', json_encode($links);
<script type="text/javascript">
<?php
echo 'var $image_paths = new Array();';
for ($i = 0; $i < count ($_child_products); $i++)
{
echo '$image_paths[';
echo $i;
echo '] = "'; // Here the starting of quotes.
echo $this->helper('catalog/image')->init($_child_products[$i], 'image');
echo '";'; // Here the ending of quotes.
}
?>
document.getElementById('main-image').href = $image_paths[1];
</script>
This should work now. Hope it helps.

How to make this code more readable

This is a part fo php code, which use the contentArray, which is a JSON, and generate the UI to the user, it generate html tags, also, it generate js code too.... It works, but I think the code is pretty difficult to read and maintain, any ideas??? thank you.
for($i = 0; $i < count($contentArray); $i++){
if($i %2 == 0){
echo ("<li class='even_row'>");
}else{
echo ("<li class='odd_row'>");
}
$content = $contentArray[$i];
echo("<textarea class='userdata' id='user_data_textarea_".$content->{'m_sId'}."'>");
echo($content->{'m_sDataContent'});
echo("</textarea>");
echo("</li>");
echo("<script type='text/javascript'>");
echo("$('#user_data_textarea_".$content->{'m_sId'}."').bind('keydown', function(e){");
echo(" TypingHandler.handleTypingInUserDataTextArea(".$content->{'m_sId'}.", e);");
echo(" });");
echo("</script>");
}
first for your odd and even styling there is not need for a class just use css
here is info on that
then in php only echo what you need in one line
$count = count($contentArray);
for($i = 0; $i < $count; $i++){
$content = $contentArray[$i];
echo('<li><textarea class="userdata" id="user_data_textarea_"'.$content->{'m_sId'}.'">'.$content->{'m_sDataContent'}.'</textarea></li>');
}
and lets put the jquery in the html page away from php
we get can get every item by using starts with selector
$('[id^=user_data_textarea_]').bind('keydown', function(e){
var id = this.id.str_replace("user_data_textarea","");
TypingHandler.handleTypingInUserDataTextArea(id, e);
});
One tip on your "for" loop, you should calculate the count of $contentArray before the loop. Every time the loop executes, it has to call that function.
$count = count($contentArray);
for ($i=0; $i<count; $i++) {
// ...
}
You could try real HTML:
<?php
for($i = 0; $i < count($contentArray); $i++){
$rowClass = $i %2 == 0 ?'even_row' : 'odd_row';
?>
<li class='<?= $rowClass ?>'>
<textarea class='userdata' id='user_data_textarea_<?=$content->{'m_sId'}?>'>
<?= $content->{'m_sDataContent'} ?>
</textarea>
</li>
<script type='text/javascript'>
//etc...
</script>
<?php } ?>
It should look something like this, for better readability in the IDE.
<?php
foreach($contentArray as $content){
?>
<li>
<textarea class="userdata" id="user_data_textarea<?php echo htmlentities($content['m_sId']); ?>">
<?php echo htmlspecialchars($content['m_sDataContent']); ?>
</textarea>
<script type="text/javascript">
$('#user_data_textarea_<?php echo htmlspecialchars($content['m_sId']); ?>').bind('keydown',function(e){
TypingHandler.handleTypingInUserDataTextArea('<?php echo htmlspecialchars($content['m_sId']); ?>',e);
});
</script>
</li>
<?php
}
You could remove the ( ) from the echo statements, they're not necessarily needed and might help make it look a little neater...
That actually looks pretty understandable to me; I could figure out what you're doing without difficulty. The only difference I would suggest would be the use of ternary operators for the row class:
echo "<li class='".( ($i%2 == 0) ? "even" : "odd" )."_row'>";
...but that's just me, some would find that MORE confusing, rather than less. I personally like putting it all in one line.
Personnaly, I like to use printf to write html code in php. It could look like:
for($i = 0; $i < count($contentArray); $i++){
printf("<li class='%s'>", $i % 2 ? "odd_row" : "even_row");
$content = $contentArray[$i];
printf("<textarea class='userdata' id='user_data_textarea_%s'>%s</textarea>",
$content->{'m_sId'},
$content->{'m_sDataContent'});
echo("</li>");
echo("<script type='text/javascript'>");
printf("$('#user_data_textarea_%1$s').bind('keydown', function(e){
TypingHandler.handleTypingInUserDataTextArea(%1$s, e);
});",
$content->{'m_sId'});
echo("</script>");
}
<?php
foreach($contentArray as $content){
$class = ($i %2 == 0) ? "even_row": "odd_row"; ?>
<li class="<?php echo $class ?>">
<textarea class='userdata' id='user_data_textarea_<? echo $content['m_sId'] ?>'>
<? php echo $content['m_sDataContent'] ?>
</textarea>
</li>
<script type='text/javascript'>
$('#user_data_textarea_<?php echo content['m_sId'] ?>').bind('keydown', function(e){
TypingHandler.handleTypingInUserDataTextArea(<?php $content['m_sId'] ?>, e);
});
</script>
<?php } // end foreach ?>
jQuery code should be already in the HTML, using some main selector and not binding elements one by one, it not makes sense for me. That should clarify your code.
for($i = 0; $i < count($contentArray); $i++){
$content = $contentArray[$i];
echo "<li class='" . (($i %2 == 0) ? "even_row" : "odd_row") . ">";
echo "<textarea class='userdata' id='user_data_textarea_".$content->{'m_sId'}."'>";
echo $content->{'m_sDataContent'};
echo "</textarea>";
echo "</li>";
}
ADDED
A generic case:
$(function() {
$('.userdata').click(function() {
some_function($(this).attr('id');
});
})
That is, bind using a class selector and late use some unique identifier for doing the job.
Put everything in arrays, then echo them at the END of your loop.
// Put each item in the array, then echo at the end
$items = array();
$js = array();
// I'm assuming that your content array has numeric keys
// if not, use the for statement from your original code
foreach ($contentArray as $i => $content)
{
// using sprintf
$items[] = sprintf('<li class="%s_row"><textarea class="userdata" id="user_data_textarea_%s">%s</textarea></li>'
, ($i % 2) ? 'even' : 'odd'
, $content->m_sId
, $content->m_sDataContent
);
// or just plain old concatenation
$js[] = "$('#user_data_textarea_{$content->m_sId}').bind('keydown', function(e){TypingHandler.handleTypingInUserDataTextArea({$content->m_sId}, e);});";
}
echo "<ul>" . join("\n", $items) . "</ul>\n"
. '<script type="text/javascript">' . join("\n", $js) . "</script>\n";
Separate your content and code using for example smarty. It requires some infrastructure investment in the short term, but improves maintenance in the long run.
Reflecting the comments, let's then treat PHP as a real templating language.
$contentCount = count($contentArray);
for($i = 0; $i < $contentCount; $i++)
{
$rowType = ( $i % 2 ) ? 'even' : 'odd';
$content = $contentArray[$i];
echo <<<EOT
<li class='{$rowType}_row'>
<textarea class='userdata' id='user_data_textarea_{$content->m_sId}'>
{$content->m_sDataContent}
</textarea>
</li>
<script type="text/javascript">
$('#user_data_textarea_{$content->m_sId}').bind('keydown', function(e)
{
TypingHandler.handleTypingInUserDataTextArea({$content->m_sId}, e);
}
</script>
EOT;
}

Categories