Script to move to next image - php

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!

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.

How to use a function with integers to return images? (PHP)

In one of my PHP pages for my website, I am trying to use a function to return a string, with three integers for the arguments. The strings in files 1 & 2 are for the same thing (One is name, the other is link). I've got something similar to this:
File1:
<?php
return array("Str0", "Str1");
?>
File2:
<?php
return array("http://example.com/Link0.png", "http://example.com/Link1.png");
?>
File3:
<?php
$names = include 'file1.php';
$links = include 'file2.php';
function imgsrc($int1, $int2, $int3){
return '<img title="'.$names[$int1].'" src="'.$links[$int1].'" /><img src="http://example.com/img.png" />';
}
?>
I have 5 images there. Images 2 and 4 are always the same, images 1, 3, and 5 are most of the time different, depending on the arguments I put. I echo the function out like this:
echo imgsrc(0, 0, 1);
I repeat that every time I want to have the 5 images, yet it only shows boxes. The HTML when I press F12 in the site only shows this:
<img src="" width="40px" height="40px" title="">
I'm trying to get it to show images with the title.
Fixed the problem. Instead of using integers, I used another file with arrays and used those ints to get the array value of the original files.

How to connect mySQL to SVG using RaphaelJS?

I am trying to link a MySQL DB to an SVG image to dynamically change the SVG elements with Raphael JS.
I have a MySQL DB where I query using PHP and display the results in table form to an html page: (The script below works and displays the username and a picture only when the condition of the timestamp is met.)
<?php
mysql_connect("","","");
mysql_select_db("");
$res=mysql_query("select username, picture from 'table' WHERE status > UNIX_TIMESTAMP(NOW()) - 300");
echo "<table>";
if (!$res) {
die("Query to show fields failed");
}
$fields_num = mysql_num_fields($res);
echo "<h1>Table:Status</h1>";
echo "<table border='1'><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($res);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
while($row=mysql_fetch_array($res))
{
echo "<tr>";
echo "<td>"; echo $row["username"]; echo "</td>";
echo "<td>"; ?> <img src=" <?php echo $row["picture"]; ?>" height="50">
<?php
How can I take the similar concept above of displaying the results in table form to an SVG image where the SVG elements will change/update only when the query condition is met?
Here is my sample SVG image with 5 elements:
<polygon fill="#B2B2B2" points="150.3,8.8 203.8,31.7 169.8,91.4 133.4,75.8 "/>
<circle id="circleT3" circle fill="#FFFFFF" cx="163.1" cy="53.6" r="7.3"/>
<circle id="circle3_1" circle fill="#CCCCCC" cx="184.5" cy="82.4" r="7.3"/>
<circle id="circle3_5" circle fill="#CCCCCC" cx="136.6" cy="27.2" r="7.3"/>
<circle id="circle3_4" circle fill="#CCCCCC" cx="166.4" cy="7.3" r="7.3"/>
Can someone point me to some sample code or tutorial? Or is there a better way to do this? Thanks.
EDIT:
In MySQL DB I have a column for username, password and timestamp. When a user logs into webpage the timestamp updates. The PHP code above is used to query who has logged within 5 minutes ago from current time.
What I would like to do with this information with SVGs is create a graphical representation of the login.
So each username will have their own SVG element (a circle) associated with them and when they log in/out, that SVG element (code above) will change color.
Right now I do not know how to link the username with my SVG elements so the SVG element will dynamically update like my table I query from MySQL when the timestamp changes.
The answer will depend on further information that isn't really available until the rest is written.
You could combine Snap (to modify existing inline SVG or create it) or Raphael (to create new SVG only, you can't use it to modify inline SVG), or another SVG library of choice (eg svg.js or jquery.svg maybe).
Assuming you already have something to use on the page, that is showing the logged in user, you could do something like in pseudocode...
loop user;
if( document.getElementById( userId ) ) Snap('#' + userId + '_image').attr({ fill: 'green' });
(The svg reference may be the same as the circles, but somewhere you would need some type of lookup to know which circle is which userid)
This assumes the svg is on the page. If its not, you could create it with
paper.circle(x,y,r).attr({ fill: 'green' });
If you want it dynamic (so status changes without a refresh), you may need to tie ajax calls to get status from the mysql db, but if you already have a user name displaying on the page, I'm assuming that is already taken care of.
I have successfully update the svg element color to when the user logs in, the corresponding circle will change color. So I have my svg code from illustrator. I then put in this script in my php file:
window.onload = function () {
if(document.body.innerHTML.toString().indexOf('username') > -1){
circle1_1.setAttribute("fill", "yellow");
};
};
Whenever a user logs in, the info is populated on the table in the html from the MYSQL query and the script looks to see if that username is on the page and if it is, change color of SVG element.
So it basically links the SVG element to any value/variable.
Not the prettiest code or logic out there but for anyone else doing something similar, enjoy.

Automatically create php pages

I have an issue on how to create individual php pages automatically.
I have already created a page called catalog.php.
In catalog.php, mySQL query would take place, querying:
$link = mysql_connect("localhost", "root", "");
mysql_select_db("photodb", $link);
$sql = "SELECT id, title, caption, comments, imagelink, year FROM photo";
Then this query would loop and display the contents on catalog.php side by side:
<ul class="grid">
<?php while ($row = mysql_fetch_assoc($result))
{ ?>
<li>
<p class="image"><img src="getImage.php?id=<?php echo $row['id']; ?>" alt="" width="175" height="200" /></p>
<p class="name"><?php echo $row['title']; ?></p>
<p class="year"><?php echo $row['year']; ?></p>
</li>
<?php } // while
?>
</ul>
where class="grid" would arrange all the queried data side by side, with image, title and year being displayed.
However, one requirement that i need is that whenever i click on any of these images, it should link to its own php page(individual.php) to show a detailed image, title, caption and author's comments. An elaboration is shown below:
Title
IMAGE Caption
Author's comments
An example:
Picture of bridge
IMAGE This image was taken in paris
Low Shuttle Speed
In the above, IMAGE, caption, title, author's comments are found in the same database "photodb" in the same table "photo"
My issue here is as follows:
Is there a way to create such pages automatically? The reason being is, if I create them manually I would have a hard time because my database has more that 100 entries.
In the <a href=""> tag as seen in catalog.php, what should the values be?
I already have a template for such a "individual.php" page. An example of he structure is follows:
<body>
<p class="title">
London Bridge</p>
<p class="caption">
Image taken in summer 2009<br /><br /></p>
<p class="image">
<img border="0" class="floatleft" src="imagelink" width="250" height="400" />
Low Shuttle Speed
</p>
</body>
How can i change this structure to suit my requirements?
Four. Can such "individual.php" url be renamed to something else with a unique id? Each image found in the database has their own unique ID.
Five. I have already queried the database in catalog.php. Can i somehow reuse this query individual.php?
In case you are wondering, getimage.php is as follows:
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$link = mysql_connect("localhost", "root", "");
mysql_select_db("photodb", $link);
$sql = "SELECT imagelink FROM photo WHERE id=$id";
$result = mysql_query($sql, $link);
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo file_get_contents($row['imagelink']);
?>
Many thanks for reading my questions.
Your last code snippet essentially answered your question - you'll create another page and pass a variable to it through the URL ($_GET). So your URL may look like "individual.php?id=25" which would pull the image with the ID of '25'. $_GET['id'] would be '25' in this example.
I also noticed you are using the "root" user for the MySQL connection. I would strongly advise against that.
http://www.1stwebdesigner.com/tutorials/getting-started-php-dynamic-content/
http://www.greensql.com/articles/mysql-security-best-practices
With reference to #Nathan Loding. I would also use
mysql_real_escape_string()
Obviously to prevent mySQL attacks. Judging by some of your code above, I guess your new or an "OLDISH" weby copy and paste coder??
These functions will help and help you learn too.. very easy to do this... so..yes ..You can use file functions.
fopen()
See also Appendix M, fclose(), fgets(), fread(), fwrite(), fsockopen(), file(), file_exists(), is_readable(), stream_set_timeout(), popen(), and stream_context_create().

PHP: Read a variable at top present at bottom

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.

Categories