PHP: Read a variable at top present at bottom - php

Is there a way to read a variable at top which is defined some where at the bottom.
Here is an example of such situation:
<!--this image is somewhere on top of the page-->
<img src="/<?php print logoPath(); ?>" border="0" />
// this code is somewhere on bottom of the page
$logo_query = "select logo_path from table where id = $row->user_id";
$res_logo = mysql_query($logo_query) or die(mysql_error());
$row_logo = mysql_fetch_object($res_logo);
$logo_path = $row_logo->logo_path;
function logoPath()
{
global $logo_path;
return $logo_path;
}
I tried to use that function to return value but even that doesn't seem to work.
Any solution?
Thanks

No, in PHP all instructions are executed sequentially so you cannot read a variable that hasn't yet been defined. You must move the code that sets the value of $logo_path above the place where you call the logoPath() function.
Alternatively you could put the sql code in the logoPath() function, which would allow you to have the function that returns the logo path below the place where you call the function.

No, but there is a way to do it with jquery:
<img id="image" src="" border="0" />
// this code is somewhere on bottom of the page
$logo_query = "select logo_path from table where id = $row->user_id";
$res_logo = mysql_query($logo_query) or die(mysql_error());
$row_logo = mysql_fetch_object($res_logo);
$logo_path = $row_logo->logo_path;
function logoPath()
{
global $logo_path;
echo "<script type='text/javascript'> $('#image').src('".$logo_path."');</script>";
}
It's kinda stupid, but it should work.

What you can do is use a Div tag and make the position on top of the page. This way the code can be executed at the button but the results will show on top.

Related

PHP check if file_exists without extension then Ajax a div with appropriate media tag (img or video) based on filepath

First posting here. I know inline php is not preferred but I haven't converted all my scripts to echo json_encoded arrays to work in javascript on the client side...so for now, I have inline php.
I do not know the extension of the user uploaded media because it could be a jpg,mp4,etc and upon upload it goes into a media folder with the user id as an identifier.
When my user first loads the div (and html page), the php script cycles through an array and does a fetch_assoc from sql query to the database each time; It returns the (media_id #) and prints out an li with the respective media displayed next to some other values from the query.
I only know the (media_id) and the file path name without the extension. When the page first loads, everything works great and the file_exists function returns correctly.
THE PROBLEM
When I AJAX the div and do the query again, because the user added a row to the database, the new list prints out with all info, BUT the file_exists function doesn't recognize the exact same paths as before and I don't have an img or video on the page.
I copy/pasted the exact same code from the original div and put it in a file for ajax to re-query and print the new li's.
All variables are the same and when I hard code a test filepath, it prints fine. Maybe there's a caching issue?
THE CODE
<?php
$result=$conn->query($select);
$row=$result->fetch_assoc();
?>
<li>
<?php
if ($row['count']>0) {
echo "<div class='media-container'>";
$pathname = "uploads/".$row["id"]."media1";
$testjpg=$pathname.".jpg";
$testjpeg=$pathname.".jpeg";
$testpng=$pathname.".png";
$testmp4=$pathname.".mp4";
if (file_exists($testjpg)==TRUE || file_exists($testpng)==TRUE || file_exists($testjpeg)==TRUE) {
echo '<img src="'.$pathname.'">';
}if(file_exists($testmp4)==TRUE) {
echo "<video></video>";
}
echo "</div>";
}?>
</li>
I could use some advice on how to fix this and how to print appropriate media tags on unknown media types.
THE OUTPUT
<div class='media-container'>
</div>
DEBUGGING ATTEMPTS
echoing the exact file path of a known image in an <img> tag works fine. putting echo'test'; inside the file_exists case does nothing.
--
Solution (Kind of)
So I've used html's onerror before and I found a workaround, though I'd still like to know why I was getting an error. PSA this uses JQuery but javascript works too:
My Solution
<script>
function img2video(el, src) {
$( el ).replaceWith( '<video class="videoClass"><source src="'+src+'" type="video/mp4"></video>' );
}
</script>
<body>
<img style="width:100%" onerror="img2video(this,'<?php echo$pathname;?>')" src="<?php echo$pathname;?>">
</body>
Alright, so here's the final answer I made to best fit the problem using glob:
Javascript:
function img2video(el,src,place) {
if (place=='type') {
$( el ).replaceWith( '<video controls controlsList="nodownload" disablePictureInPicture style="width:100%;object-fit:contain;" preload="auto"><source src="'+src+'" type="video/mp4"></video>');
}
}
PHP:
<?php for ( $i=1; $i <= $limit; $i++) {
$path ="[DIRECTORY]/".$row["id"]."media".$i;
$path = (!empty(glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0])) ? glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0] : false;?>
<div>
<img onerror="img2video(this,'<?php echo$path;?>','type',<?php echo$row["id"];?>,<?php echo$i;?>)" src="<?php echo$path;?>">
</div>
<?php } ?>
I don't know how to mark as duplicate, if someone could help with that. My answer uses Glob_Brace from #Akif Hussain 's response on This Question.

Problems using a variable as array key in html5 script

I'm currently trying to start using php for some procedural generations and wanted to display my functions with a bar chart:
<?php
$seed = 58521672597513854781922;
global $randomArray;
for ($i=-1000; $i<1001; $i++) {
$temp = $seed/($i+0.1)^0.5;
$tempRes = $temp.'';
$randomArray[$i] = $tempRes[5];
}
?>
<div>
<canvas id="c3" width="600" height = "200" style="border:solid 1px #000000;"></canvas>
<div>
<button onclick="Vertical_line();return true;">draw array</button>
</div>
</div>
<script>
var c3 = document.getElementById("c3");
var c3_context = c3.getContext("2d");
function Vertical_line() {
<?php
for($j=0;$j<sizeof($randomArray);$j++){
$height = 100 - 10*$randomArray[$j];
?>
c3_context.moveTo(<?php echo 300+$j;?>, 200);
c3_context.lineTo(<?php echo 300+$j;?>, <?php echo $height;?>);
c3_context.strokeStyle = "red";
c3_context.stroke();
<?php }?>
}
</script>
i don't understand why the variable $j as key reference in my array doesnt work. If i replace it by numbers manually to draw a single entry of my array it works without problems, if i set a variable as absolute number and use it as key it works too, just when i use a variable that changes its value it wont display anything.
Help is appreciated :)
Ok, thanks for helping out, found the error, was a problem with the negative key for my array, simple oversight :), thanks # u_mulder for reminding me to look at the source code, i had to scroll quite a while to see the error ^^
You cannot run Php inside ofJavascript, Php always runs as soon as the page loads, you want to create a JS function to do the job u wish

Angular.js modal window within php echoes not working

I'm using code from this angular.js modal window tutorial by Jason Watmore: http://jasonwatmore.com/post/2016/07/13/angularjs-custom-modal-example-tutorial
I'm trying to implement an angular.js modal window within a php partial. Here is the code where I believe there's a problem:
<div id="screenings">
<?php
//MySQL database connection established
...
while ($row = mysqli_fetch_array($result)){
echo "<div class='img_div'>";
echo "<img class='modal_img img_screenings' ng-click=\"vm.openModal('custom-modal-1')\" src='images/".$row['image']."' >";
...
echo "</div>";
}
?>
</div>
<modal id="custom-modal-1">
<div class="modal">
<div class="modal-body">
<img id="popup_img" src="#">
</div>
</div>
<div class="modal-background"></div>
</modal>
<script>
$('.img_div').on("click", function() {
var source = ( $('.modal_img').attr("src") );
alert(source);
$('#popup_img').prop('src', this.src);
});
</script>
The First Problem
The while loop spits out a bunch of images. The script at the bottom should then grab the src of whichever image is clicked and then alert that src in a pop-up message. However, it only alerts the src of the first image in the while loop regardless of which image of the bunch is clicked. I've tested this script outside of the while loop on separate img elements with different src attributes, and it works fine outside of the echoed while loop.
The Second Problem
Within the while loop, there is an ng-click in the second echoed statement that just isn't working. In my app.js file, here is the controller code that ng-click=\"vm.openModal('custom-modal-1')\" should go to (the slashes are because of the echo statement):
app.controller('screeningsController', ['$scope', '$log', "ModalService", function($scope, $log, ModalService){
var vm = this;
vm.message = "Hello World!";
$log.log(vm.message);
vm.openModal = openModal;
vm.closeModal = closeModal;
function openModal(id){
ModalService.Open(id);
}
function closeModal(id){
ModalService.Close(id);
}
};
}]);
Right after the var vm = this; statement, I'm trying to output a message to the browser console as a test, but it's not working. Maybe my syntax is wrong?
here's a couple quick thoughts. In the first portion, I don't think you were actually capturing the correct click. I added a variable to pass into the on click function to select the one that was actually clicked.
As far as the php, sometimes its easier to toggle out of php and do a chunk of html. If you're passing a lot of html chunks you might want to consider doing output buffering.
<?php
while ($row = mysqli_fetch_array($result)){ ?>
<div class='img_div'>";
<img class="modal_img img_screenings" ng-click="vm.openModal('custom-modal-1')" src="images/<?php echo $row["image"]; ?>" />
</div>
As far as the jquery on the page:
you need to grab the actual node with the click event - the "e" is a common convention for that, but its really just a variable
$('.img_div').on("click", function(e) {
var source = $(e).attr("src"); // here you grab the actual attribute
alert(source);
$('#popup_img').attr('src', source);
});
i'm assuming you actually want to set the img src attribute in your target modal here.

How can I display a random image from a php array using jQuery?

I have been trying to create a random picture display animation, in the style of a slot machine wheel. The user clicks 'spin' and a gif image appears, giving the effect of a slot wheel spinning. When the wheel stops, the spinning effect gif image is replaced by a random member's picture. However, the random member's picture is not appearing. In firebug, I can see that the array is being populated correctly, and the member pictures (with correct url) are all present.
The issue seems to be that the jQuery script is not prepending the tag to the in which the image is to appear, and I cannot work out why.
The PHP to gather the information for the array is here:
$q = "SELECT id, username FROM members WHERE my_sex =:req_sex";
$stmt = $dbo->prepare($q);
$stmt->execute(array(":req_sex" => $req_sex));
while($r = $stmt->fetch()) {
$m_id = $r['id'];
$m_name = $r['username'];
$m_pic .= '"members/'.$m_id.'/minis/resized_image_'.$m_id.'_0.jpg", ';
}
$m_pic = rtrim($m_pic, ', ');
and the jQuery which I am sure is incorrect somewhere is here:
$(document).ready(function(){
images = new Array(<?php echo $m_pic; ?>);
var length = images.length;
var which = Math.round(Math.random()*(length-1));
$('<img src="'+images[which]+'" alt="" class="randomMember"/>').prependTo('div#wheel');
};
I have been playing around with this and tried various methods, and using firebug to investigate, the best I have managed to achieve is to get the following line showing in the html.
<img class="randomMember" alt="" src="" />
I cannot remember how I did this, but I think it was using document.write and not wrapping it in a function. I have only been using javascript and jQuery for a week or so, and despite a whole lot of Googling and reading up, I cannot see why this isn't working out. Thanks in advance!
EDIT: the html is as follows:
<div class="hidden_sidebox">
<div id="chat_view">
<div id="wheel">
<img src="members/0/default_pic.jpg" alt="" class="preSpin" />
<img src="images/randomChatWheel.gif" alt="" class="spinAnimation" style="top: -220px;" />
</div>
//here is where the problem jQuery script is...I think this is the correct place for it, as it will prependTo the previous div element (which I have explicitly specified anyway, just in case)
<div id="btnPanel">
<div id="chatButton">CHAT</div>
<div id="spinButton">SPIN</div>
</div>
<div id="chatSplash"></div>
</div>
</div>
and the function for the wheel spin (which works perfectly apart from the final image failing to display) is here:
$(document).ready(function() {
$("div#chatSplash").click(function () {
$("div#chatSplash").slideUp("fast");
$('img.randomMember').hide();
$('img.spinAnimation').hide();
$('div#spinButton').removeClass('ButtonDisabled');
$('div#chatButton').removeClass('ButtonDisabled');
});
$("div#spinButton").click(function () {
$("img.preSpin").hide();
$("img.spinAnimation").show();
$('div#spinButton').addClass('ButtonDisabled');
$('div#chatButton').addClass('ButtonDisabled');
setTimeout(function(){$("img.spinAnimation").hide();
$('img.randomMember').show();
$('div#spinButton').removeClass('ButtonDisabled');
$('div#chatButton').removeClass('ButtonDisabled');
}, 2500);
});
});
There is a simple error here, you're not closing parentheses. You have:
$(document).ready(function(){ . . .};
Which should be
$(document).ready(function(){ . . .});
Try this in PHP:
$pictures = array();
while($r = $stmt->fetch()) {
$pictures[] = sprintf('members/%d/minis/resized_image_%d_0.jpg', $r['id'], $r['id']);
}
and then in JS:
images = <?php json_encode($pictures); ?>;

Script to move to next image

I am writing a script to display images on my site. The images are stored on the server and the source (path) is on a mySQL database. I want to be able to move to the next (or previous picture) by invoking two php functions I have made to do so. The code I have written so far is:
<?php
require "db_connection.php";
$query="SELECT source FROM photos";
$result=mysql_query($query);
$count=0;
$numberofpics=mysql_num_rows($result);
$image=mysql_result($result, $count, "source");
$num=1;
function slideshowForward() {
$num=$num+1;
if($num==($numberofpics+1)) {
$num=1;
}
$count=$count+1;
$image=mysql_result($result, $count, "source");
}
function slideshowBack() {
$num=$num-1;
if ($num==0) {
$num=$numberofpics;
}
$count=$count-1;
$image=mysql_result($result, $count, "source");
}
?>
The html portion to display the images is:
<!-- FORWARD AND BACK FUNCTIONS-->
<a class="back" href="http://mywebsite.com/discoverandrank.php?function=slideshowBack()"> <img src="graphics/back.png"/></a>
<a class="next" href="http://mywebsite.com/discoverandrank.php? function=slideshowForward()"><img src="graphics/forward.png"/></a>
<!--DISPLAY MIDDLE PHOTO-->
<div id="thepics">
<img src="http://www.mywebsite.com/<?php echo $image; ?>" name="mypic" border=0 height="300" width="500"></img>
</div>
I'm pretty sure that the php script is incrementing/decrementing the count currently for the image, but I think the problem might be because the html (specifically img src="....") part is not re-evaluated when the count of the image increases?
Mmm there are two things to point out here:
I think that passing a function name as a parameter on an action is not a good idea, instead you should user something like: "http://mywebsite.com/discoverandrank.php?op=next&current=10" and then evaluate the op and current value to take some action.
For gettting the next picture from database you could use something like this:
"Select source FROM photos LIMIT "current+1" , 1"
For gettting the previous picture from database you could use something like this:
"Select source FROM photos LIMIT "current-1" , 1"
This way you dont need to keep counters and stuff, just have to check if those queries return any data.
Hope this helps!

Categories