I have a mysqli database and form which allows me to store an id, name and photo. The path of the photo is set to an "images" folder on the server. I have a query which can
SELECT * FROM images WHERE name = $pagetitle.
This works absolutely fine, outside of the javascript slideshow. When i put a php command in the javascript where it is looking for which images to display, the js only shows 1 image, and not ALL images.
Any help would be appreciated, thanks.
The section of the code in question is below...
index.php
<!-- Image Slide Show Start -->
<div style="display: flex; justify-content: center;">
<img align="middle" src="" name="slide" border=0 width=300 height=375>
<script>
<?php
require('dbconnect.php');
$data = mysql_query("SELECT * FROM images WHERE name= '$pagetitle'");
$image = mysql_fetch_array( $data );
?>
//configure the paths of the images, plus corresponding target links
slideshowimages("<?php echo "/images/".$image['photo'] . ""?>")
//configure the speed of the slideshow, in miliseconds
var slideshowspeed=2000
var whichlink=0
var whichimage=0
function slideit(){
if (!document.images)
return
document.images.slide.src=slideimages[whichimage].src
whichlink=whichimage
if (whichimage<slideimages.length-1)
whichimage++
else
whichimage=0
setTimeout("slideit()",slideshowspeed)
}
slideit()
</script> </div><br><br>
<!-- Image Slide Show End -->
your update query have syntax errors, use , between fields, also you must contain strings in 2 ' :
$query = "UPDATE page_content SET PageTitle='$pageTitle',
PageContent='$PageContent', PageContent2='$PageContent2' WHERE PageId='$PageId'";
You have missed , between fields and '' around variables in your query.
$sql = "UPDATE page_content SET PageTitle='$pageTitle',
PageContent='$PageContent', PageContent2='$PageContent2'
WHERE PageId='$PageId'";
// check query executed successfully or get error
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
OR
$result = mysqli_query($sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error(), E_USER_ERROR);
Hope it will help you :)
Try this:
$sql = "SELECT * FROM images WHERE name= '$pagetitle'";
$result = $conn->query($sql);
$directory = '';
while( $image = $result->fetch_assoc() )
$directory .= ($directory != '' ? "," : '') . ('"/images/'.$image["photo"] . '"');
// Check if it was successfull
if($directory != '') {
// if there are images for this page, run the javascript
?><script>
//configure the paths of the images, plus corresponding target links
slideshowimages(<?php print $directory ?>)
Related
I wanna update an image in my database table. So first I made a MySQL query to display already uploaded Image in the HTML form web page. And after that, I made another query to update Image... So now I want that If I don't choose any Image for the update then already uploaded Image should be selected as default input in the form. So How can I set the already uploaded image as default input in the form? Please help me out...
<img src="../images/<?php echo $post_image ?>" width="100px">
<input type="file" name="image" class="form-control-file">
<!-------------------Display Image--------------------->
<?php
$query = "SELECT * FROM posts WHERE post_id=$post_id ";
$getPost = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($getPost)) {
$post_image = $row['post'];
}
?>
<!------------------Update Image------------------->
<?php
if (isset($_POST['publish_edit'])) {
$post_image = $_FILES['image']['name'];
$post_image_temp = $_FILES['image']['tmp_name'];
move_uploaded_file($post_image_temp, "../images/$post_image");
$query = "UPDATE posts SET ";
$query .= "post_image = '$post_image' ";
$query .= "WHERE post_id = $post_id ";
$editPost = mysqli_query($connection, $query);
}
?>
check if the image input is empty or not. if it is empty, leave image database column in it's previous state.
I am using a php script to display images stored as blobs in my database.
I used to display them with the following script.
<?php
if(!empty($_GET['user_id'])){//script to display an image from the database you basicly just get the id from the picture in matter and fucking acess it
include_once "DBH.php";
//Get image data from database
$id = mysqli_real_escape_string($conn, $_GET['user_id']);
$result = $conn->query("SELECT image FROM profilePictures WHERE user_id = $id");
if($result->num_rows > 0){
$imgData = $result->fetch_assoc();
header("Content-type: image");
echo $imgData['image'];
}else{
echo 'Image not found...';
}
}
?>
In the context where
<img src = 'displayProfilePicture.php?user_id=n'>
The div containing the divs are updated frequently and to update the users image seems like alot of unnecessary processing. I want to cache the profilepictures in the webpage so that i dont have to query them from the database every time. I started reading alot about how you could cache the images but could not find any content on how to display the cached images.
This is a problem for me as the images flicker for a bit every time the img is updated with the php script. In an optimal world i see that the img load one time and then after that it does not have to load.
The context wich i use the display img script is in a chat that is updated with a timer-interval within an ajax-request
$("#chatlogs").load("logs.php");
logs.php
if(isset($_SESSION['chatRoomId'])){
while ($extract = mysqli_fetch_array($result1))
{
$from = $extract['from'];
//make an object to echo.
if($from == $id){
echo "<div class='chatContainer self'>
<div class = 'imgContainer'>
<img src='displayProfilePicture.php?user_id=$selfId'>
</div>
<div class='content'>
<div class = 'message'>
". $extract['msg'] ."
</div>
</div>
</div>";
}else{
echo "<div class='chatContainer friend'>
<div class = 'imgContainer'>
<img src='displayProfilePicture.php?user_id=$guestId'>
</div>
<div class='content'>
<div class = 'message'>
". $extract['msg'] ."
</div>
</div>
</div>";
}
}
}
I think this is what you looking for:
<?php
if(empty($_GET['user_id']) || !preg_match( '/^[0-9]+$/' , $_GET['user_id'])){
header( '400 Bad Request' );
exit(1);
}
include_once "DBH.php";
$user_id = intval( $_GET['user_id'] );
$result = $conn->query("SELECT image FROM profilePictures WHERE user_id = $user_id");
if($result->num_rows == 0){
// Not Found
header('404 Not Found');
exit(1);
}
$imgData = $result->fetch_assoc();
header("Content-type: image");
$cache_for = 3600; // One hour in seconds
$cache_until = gmdate("D, d M Y H:i:s", time() + $cache_for) . " GMT";
header("Expires: $cache_until");
header("Pragma: cache");
header("Cache-Control: max-age=$cache_for");
echo $imgData['image'];
exit(0);
Comments
First I checked if the user_id is supplied in the request, if so then check if it was a valid number if it doesn't then respond with a 400 error.
And also I have removed a SQLi in your code src='displayProfilePicture.php?user_id=-1 or 1=1.
And I have set the caching headers, so the browser will cache the image for an hour.
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
I'm trying to use thumbnails retrieved from database. PHP is working fine and displaying my thumbnails. I don't know how to get the id from database into the imageID for JavaScript function and getElementById, to display as full size when clicked. I can do straight JavaScript inline onsubmit in my code. The inline JavaScript is working; the thumbnail is being displayed, and when clicked a full size shows, but I want to use my database retrieved images to show the full size image when clicked. Do you think you can help me with my code?
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<script type="text/javascript">
//function that shows full sized image of the thumbnail
function showImage(imageID) {
//first hide all images
document.getElementById('image1').style.display = 'none';
//then display the one that had its thumbnail clicked.
document.getElementById(imageID).style.display = '';
}
</script>
</head>
<body>
<h1></h1>
<?php
$host = "localhost";
$user = "root";
$pass = "";
$database = "travel1";
$conn = new mysqli($host, $user, $pass, $database);
if ($conn->connect_error)
die ("Unable to connect to database: " . $conn->connect_error );
$sql = "select * from what_to_do
where DESTINATION='NEW YORK CITY'";
$result = $conn->query($sql);
if ($result->num_rows >= 0) {
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<td>".$row["THUMBNAIL"]."</td>";
}
echo "</table>";
}
else {
echo "You have no destinations";
}
$conn->close();
?>
<p>
<img id="image1" alt="" src="images/NewYork/Pick7/9-11show.jpg"
style="display: none" />
</p>
<p>
<img alt="" src="="images/NewYork/Pick7/9-11thumb.JPG"style="width:100px;
height:100px" onclick="showImage('image1')" />
</p>
In this code the second img tag is closed prematurely, like src="something" etc etc. If that tag were properly formed, I think this should work?
Otherwise, you would just do something like " src="/blah" />
Hopefully that answers your question?
And then for the I onclick function just do essentially the same thing.
I'm going to presume a lot, but here goes!
The above answer is correct, you are prematurely closing an image tag at the bottom of your code, it should be like this:
<img alt="" src="images/NewYork/Pick7/9-11thumb.JPG" style="width:100px;
height:100px;" onclick="showImage('image1')" />
But otherwise there are a few other issues to address...
First, by typing in the specific name of the destination for each query on every page you'll be defeating the purpose in using a database! Just like you've mentioned, you need to use the ID and pull in the data accordingly.
To do this you need to define what the ID is by letting the user select the destination on a previous page/section(in your example a destination list might be appropriate with all the destinations in some kind of order, be that ascending or descending ect... PHP has a few different ways.)
So first, the query to sort by ID is:
SELECT * FROM travel1 order by id desc
and then to set the ID in the URL when the destination link is clicked, here's an example link using php to carry the ID to the next page:
more info
Once you get to the destination info page(that's what I'm calling your above code), filter your data so that you can access the specific destination by ID by firstly adding this to your page(after you've connected to the database that is):
<?php
if(isset($_GET['id'])){
$id = preg_replace('#[^0-9]#i', '',$_GET['id']);
$result = $con->query("SELECT * FROM travel1 WHERE id='$id' ");
while($rows = $result->fetch_assoc()) {
echo "<td>".$row["THUMBNAIL"]."</td>";
}
} else {
echo "We're having some issues...";
}
?>
The above code will pick up the database ID from your URL which was carried over from the previous page(your new destination list) and can be echoed out like your other links such as:
'echo "<td>".$row["THUMBNAIL"]."</td>";'
I hope this helped! =D
Very new to php... bear with me!
I'm creating a photography website and am stuck on a particular page. Ultimately I need the page to be a form with a dynamic number of inputs. It will be a dynamic visual representation of folders (or "galleries") on my web host server. Each div block will contain the first image from the folder along with the name of the folder - the heading text and image should both be clickable and act as a submit button to continue to the album.php page, passing the name of the folder via a GET method.
The first problem I had was trying to get rid of the submit button from a form, and replace with my album thumbnail and album title in an <a> tag. Apparently via javascript, and I managed to get this to work - kind of. I've gotten the page to a state where there is a form, with multiple inputs, but every single folder name is now being passed in the URL (e.g. mywebsite.com/album.php?name=album1&name=album2&name=album3) and I'm absolutely stuck!
The code is included, so if someone could have a look over and offer some guidance or point me in the right direction (and offer any other newbie tips!) it would be much appreciated.
Cheers
Lee
<form id="album" method="get" action="album.php">
<?php
$basepath = 'images/portfolios/public/';
$results = scandir($basepath);
foreach ($results as $result) {
if ($result === '.' or $result === '..') continue;
if (is_dir($basepath . '/' . $result)) {
//create new gallery for each folder
?>
<div class="gallery">
<?php
//get count of images in folder
$i = 0;
$path = 'images/portfolios/public/' . $result;
if ($handle = opendir($path)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($path.$file))
$i++;
}
}
//create array, and choose first file for thumbnail
$files = array();
$dir = opendir($path);
while(($file = readdir($dir)) !== false)
{
if($file !== '.' && $file !== '..' && !is_dir($file))
{$files[] = $file;}
}
closedir($dir);
sort($files);
//form input - album name for next page
echo '<input type="hidden" name="name" id="name" value="'.$result.'" />';
//the headline and image link for gallery
echo '<a href="javascript: submitform()">' . $result . ' - ('.$i.' images)<br>
<img src="'.$path.'/'.$files[0].'" />
</a>';
?>
</div> <!-- end gallery -->
<?php }
}
?>
</form>
<script type="text/javascript">
function submitform(){document.forms["album"].submit();}
</script>
change your code from:
echo '<a href="javascript: submitform()">' . $result . ' - ('.$i.' images)<br>
<img src="'.$path.'/'.$files[0].'" />
</a>';
to this code:
echo '<a href="admin.php?name='.$result.'">' . $result . ' - ('.$i.' images)<br>
<img src="'.$path.'/'.$files[0].'" />
</a>';