PHP Get method not working - php

I am able to retrieve the name but why can't I show the whole video inside the embed location?
This is the the whole PHP file that I am working on.
The first box is mainly about uploading the video on to the directory and database.
I am actually having problem with the second box only as the video does not appear.
<?php
include 'connect.php'; //include the php file into this php file
?>
<div id="box">
<form method='post' enctype="multipart/form-data">
<?php
if(isset($_FILES['video'])){
$name = $_FILES['video']['name'];
$type = explode('.', $name);
$type = end($type);
$size = $_FILES['video']['name'];
$random_name = rand();
$tmp = $_FILES['video']['tmp_name'];
if($type != 'mp4' && $type != 'mp4' && $type != 'wmv'){
$message = "Video Format Not Supported!";
}
else {
move_uploaded_file($tmp, 'videos/'.$random_name.'.'.$type);
mysqli_query($db, "INSERT INTO videos (id, name, url)
VALUE ('', '$name', '$random_name.$type')");
$message = "Successfully Uploaded!";
}
echo "$message";
}
?>
Select Video : <br/>
<input type='file' name="video" />
<br/><br/>
<input type="submit" value="Upload" />
</form>
</div>
<div id="box">
<?php
$query = mysqli_query($db, "SELECT `id`, `name`, `url` FROM videos");
while($run = mysqli_fetch_array($query)){
$video_id = $run['id'];
$video_name = $run['name'];
$video_url = $run['url'];
?>
<?php
echo $video_name;
?>
<?php
$video = $_GET['video'];
echo "<embed src=`$video` width='560' height='315'></embed>" ;
?>
<?php
}
?>
</div>

You have backticks instead of quotes in your HTML. Change them to single or double quotes, e.g.:
echo "<embed src='$video' width='560' height='315'></embed>" ;
^ ^

You should have
if (isset($_GET['video'])) {
$video = $_GET['video'];
echo '<embed src="'.$video.'" width="560" height="315"></embed>';
}
So people can't access the page without entering a video id

Try this way, it will require you to change your database. But should work. Just read the commented out instructions I made to use it.
<div id="box">
<?php
if (isset($_GET['video'])) {
$video = $_GET['video'];
$query = mysql_query("SELECT * FROM `videos` WHERE `id`='$video'");
$count = mysql_num_rows($query);
if ($count!=0) {
$row = mysql_fetch_assoc($query);
$video_id = $row['id'];
$video_name = $row['name'];
$video_url = $row['url'];
echo $video_name;
echo '<embed src="'.$video_url.'" height="315px" width="560px">';
//echp <video height="315px" width="560px" controls><source src="movie.mp4" type="video/mp4"></video>
//Use the above code if you want a html5 video player.
} else {
echo 'Video does not exist!';
}
} else {
echo 'Please enter a video id!';
}
/*
How to use it:
Create a database called "videos"
Insert the following three columns:
id = varchar(225) as `primary_key`
name = varchar(225);
url = varchar(225);
To insert a video, you will need to create
a random id for the video and insert it
into the mysql database. Example
$rand = rand(111111111,999999999);
$id = md5($rand);
//example $id = 3174143713413051830531
$name = "Random video name";
$url = "http:/localhost/websitename/videos/nameofvideo.mp4";
$query = mysql_query("INSERT INTO `videos` VALUES ('$id','$name','$url')");
Then to select the video you will go to a page
video.php?video=[video id here];
video.php?video=3174143713413051830531
then the php will select the url for the video
id = 3174143713413051830531
and it will play that video.
example: video_url would be http://localhost/websitename/videos/nameofvideo.mp4
If you have any further questions,
feel free to ask me. Thanks
*/
?>
</div>
Hope this works. Thanks!

Related

how to insert multiple images to database in one row

I have made up this html form
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<input type="file" name="image1" /><br/>
<input type="file" name="image2" /><br/>
<input type="submit" name='submit' value="upload" />
</form>
this is my php code
<?php
include "conf/connect.php";
if (isset($_POST['submit'])){
$uploadpath1 = 'upload/';
$image1_name = $_FILES['image1']['name'];
$image1_size = $_FILES['image1']['size'];
$image1_type = $_FILES['image1']['type'];
$image1_url =
$image1_temp_name = $_FILES['image1']['tmp_name'];
$uploadpath1 = $uploadpath1. time() . basename($image1_name);
$image1_url = 'http://'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['REQUEST_URI']), '\\/').'/'.$uploadpath1;
////
if(empty($errors)) {
move_uploaded_file($image1_temp_name, $uploadpath1);
$success[] = 'Uploaded!';
}
}
///
if (isset($_POST['submit'])){
$uploadpath2 = 'upload/';
$image2_name = $_FILES['image2']['name'];
$image2_size = $_FILES['image2']['size'];
$image2_type = $_FILES['image2']['type'];
$image2_temp_name = $_FILES['image2']['tmp_name'];
$uploadpath2 = $uploadpath2. time() . basename($image2_name);
$image2_url = 'http://'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['REQUEST_URI']), '\\/').'/'.$uploadpath2;
////
if(empty($errors)) {
move_uploaded_file($image2_temp_name, $uploadpath2);
$success[]= 'Uploaded';
}
}
if(isset($_POST['submit'])){
$id = $_GET['id'];
$table = 'products';
mysqli_query($connect, "UPDATE `$table` SET `image1` = $uploadpath1, `image2` = $uploadpath2 WHERE `id` = $id");
}
?>
All in : image_multi.php
So when i post submit .. the images uploaded successfully but nothing updated in my table
my table
I run this link : mydomainname.com/image_multi.php?id=1
images uploaded but not appears in database at all
Thanks
Check type and length for fields 'image1' and 'image2' in your table
the problem is definitely in the mysql statement, you didn't quote the filenames that's why the update doesn't run through. in the future simply check the db log for errors.
to fix this should work
mysqli_query($connect, "UPDATE `$table` SET `image1` = '$uploadpath1', `image2` = '$uploadpath2' WHERE `id` = $id");
notice the ' enclosing your $vars, that's only for when you need strings in the rows - which you clearly need. I'm not sure the Id should be string, check to see if it's numeric.

Delete an image using link/id from database

I want to delete an image by an button called 'DELETE'.
My image is saved on the server, my image link is saved into a database table.
To delete now works great, but every user can delete every users images right now by typing in the picture id in the URL.
uploads.php
<div id="myuploads">
<?php
//Configuration
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'myimg';
$salt = "u6d5u6mj65dehjum568nuu65umk57endjzu766imm57e8u5u56";
if(isset($_SESSION['username'])){
$hash = hash('sha224', $_SESSION['username']).$salt;
}
$conn = mysqli_connect("$host", "$user", "$pass", "$db");
//Script
if(isset($_SESSION['username'])){
$uid = $_SESSION['username'];
$dir = $uid . "/";
$alledateien = mysqli_query($conn, "SELECT * FROM imglinks WHERE uid='$uid'");
foreach ($alledateien as $datei)
{
echo "<div class='pictures'> \
<img class='pbild' src='" . $dir . $datei["link"] . "'><br/> \
<form action='functions/deleteimg.php'></div> \
<input class='deleteimg' type='submit' name='deleteimg' value='DELETE'> \
<input class='post' type='submit' value='PUBLISH'></form>";
}
}else{
header("Location: ../index.php");
}
?>
</div>
deleteimg.php
<?php
include '../config.php';
$uid = $_SESSION['username'];
$username = mysqli_query($conn, "SELECT uid FROM imglinks WHERE uid='$uid'");
foreach($username AS $name) {
if(isset($_GET['deleteimg']) && $uid = $name['uid']){
$sql = "SELECT * FROM imglinks WHERE id='".$_GET['deleteimg']."' LIMIT 1";
$filepath = mysqli_query($conn, $sql);
foreach($filepath AS $value) {
unlink($value['link']);
}
$uid = $_SESSION['username'];
mysqli_query($conn, "DELETE FROM imglinks WHERE id='".$_GET['deleteimg']."' AND uid='$uid'");
}}
The links given out coming out of the imglinks table of my database.
DATABASE STRUCTURE
If you need more detail, feel free to ask.
One thing that I would suggest / do when deleting I would use an anchor tag instead of a button to delete then on the anchor tag I will have action and id as query string. then on the deleteimg.php page I will query the action and the ID if the action is delete then delete the selected id.
Then you code will look like this :
uploads.php
<div id="myuploads">
<?php
//Configuration
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'myimg';
$salt = "u6d5u6mj65dehjum568nuu65umk57endjzu766imm57e8u5u56";
if(isset($_SESSION['username'])){
$hash = hash('sha224', $_SESSION['username']).$salt;
}
$conn = mysqli_connect("$host", "$user", "$pass", "$db");
//Script
if(isset($_SESSION['username'])){
$uid = $_SESSION['username'];
$dir = $uid . "/";
$alledateien = mysqli_query($conn, "SELECT * FROM imglinks WHERE uid='$uid'");
foreach ($alledateien as $datei)
{
echo "<div class='pictures'> \
<img class='pbild' src='" . $dir . $datei["link"] . "'><br/> \
<form action='functions/deleteimg.php'></div> \
<a class='deleteimg' href='functions/deleteimg.php?action=delete&id='".$datei['id']."'>DELETE</a><br>
<input class='post' type='submit' value='PUBLISH'></form>";
}
}else{
header("Location: ../index.php");
}
?>
</div>
Then deleteimg.php
<?php
// Your connection here...
// check if session is set here...
$action = $_GET['action'];
$img_id = intval($_GET['id']);
if($action === "delete"){
$sql = "DELETE FROM imglinks WHERE id='$img_id'";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
//image delete... do something else
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
}
mysqli_close($conn);
?>
This always works for me and always easy, hope you will find it useful.
NB: Read about mysqli prepared statements, against sql injections.. You can read here
You can:
Add a boolean field to your imglinks table named say 'show', and modify your query accordingly. In this case you'll be even able to 'undelete' accidentally deleted images.
If you're short on disk space then modify <input class='deleteimg' type='submit' name='deleteimg' value='DELETE'> to <input class='deleteimg' type='submit' name='deleteimg' value='".$image_to_delete."'> so that you'll see this link in your postdata and will be able to process it
It's not so complicated, just use like this :
*Root is your root directory !
$path = root/$uid/$imgname;
$query("DELETE FROM imagetable WHERE imgname = $imgname");
And to delete the image :
unlink($path);
And just use a form to submit imgname to your script !
*For more security, you can also add $uid to your query !
You need to change your buttons like this:
foreach ($alledateien as $datei)
{
echo "<div class='pictures'> \
<img class='pbild' src='" . $dir . $datei["link"] . "'><br/> \
</div><form action='functions/deleteimg.php'> \
<input type='hidden' name='img_id' value='".$datei["id"]."'> \
<input class='deleteimg' type='submit' name='deleteimg' value='DELETE'> \
<input class='post' type='submit' name='publish' value='PUBLISH'></form>";
}
Then on deleteimg.php, get the image id and execute a delete query:
if(isset($_POST['deleteimg']) && $_POST['deleteimg'] == 'DELETE'){
$img_id = $_POST['img_id'];
mysqli_query($conn, "DELETE FROM imglinks WHERE id='$img_id'");
}
Thanks for all answers, now i've completed it myself.
deleteimg.php
<?php
include '../config.php';
$uid = $_SESSION['username'];
if(isset($_GET['deleteimg'])){
$sql = "SELECT * FROM imglinks WHERE id='".$_GET['deleteimg']."' LIMIT 1";
$filepath = mysqli_query($conn, $sql);
$test = mysqli_fetch_array($filepath);
if($test['uid'] == $uid){
unlink($test['link']);
mysqli_query($conn, "DELETE FROM imglinks WHERE id='".$_GET['deleteimg']."' AND uid='$uid'");
echo 'File successfully deleted.';
header ("Refresh: 2; ../index.php");
} else {
echo 'You do not have the permission to delete this file.';
header ("Refresh: 2; ../index.php");
}
}

Select query to match to columns

I am trying to create a user profile image feature. So far I am able to upload and select an image and display it, but I cannot figure out how to select the image specific to a user. My query was working (though with the issue described above) until I added the code below (//added is what I changed).
I was able to get my insert query to send the user's user_id with it, I just cannot figure out the select part.
My database for this is small, it just has id, user_id, img.
I want to select the img that is in my database that has the user's user_id. I am carrying the user_id with a session and that is what $user_id is.
Anyone see what I am doing wrong in my select query?
function getPhoto($con,$dest)
{
$user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" ); //added
// $result = mysqli_query($con,"SELECT * FROM `profile_img` where `img` = '$dest'");
$result = mysqli_query($con,"SELECT * FROM `profile_img` where `img` = '$user_id'"); //added
if($row = mysqli_fetch_array($result))
return $row;
return 0;
}
Edit: More code.
function getPhoto($con,$dest)
{
$user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" ); //added
// $result = mysqli_query($con,"SELECT * FROM `profile_img` where `img` = '$dest'");
$result = mysqli_query($con,"SELECT * FROM `profile_img` where `user_id` = '$user_id'"); //added
if($row = mysqli_fetch_array($result))
return $row;
return 0;
}
// Make sure all functions above are include here
// Get the database connection
$con = Connection();
// Check for post
if(isset($_POST['create'])) {
// Try uploading
$upload = UploadFile($_FILES);
// If upload fails
if(!$upload['success'])
echo '<h3>Sorry, an error occurred</h3>';
else {
// You could add error handling here based on the results of
// each function's success or failure below.
// Try to save it
$saveToDb = SaveToDb($con,$upload['file']['dest']);
// Get the profile from image name
$profPic = ($saveToDb)? getPhoto($con,$upload['file']['dest']) : false; ?>
<?php
}
}
?>
<img id="profile-pic" src="<?php echo (!empty($profPic) && $profPic != 0)? $profPic['img'] : "profile_images/default.jpg"; ?>" alt="<?php echo (!empty($profPic) && $profPic != 0)? "Profile Picture" : "No Picture"; ?>" />
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file" class="inputbarfile" onchange="readURL(this);">
<img width="400px" height="300px" id="file" src="#" alt="your image">
<input type="submit" name="create" id="signinButton" value="Upload">
</form>
This:
$result = mysqli_query($con,"SELECT * FROM `profile_img` where `img` = '$user_id'"); //added
Should be:
$result = mysqli_query($con,"SELECT * FROM `profile_img` where `user_id` = '$user_id'"); //added
Because img column holds the image path and you are comparing user id.

Mysql INSERT statement FAILING when POSTING large array

I've been searching the internet and "pulling my hair out" for days over this. It works fine on my XAMPP localhost and was working fine on my online testing server until I updated the PHP version and had to rewrite the code due to deprecated syntax.
Basically, I'm making a backend database for photography clients. One of the tables is designed to store image information. I haven't tried to store an actual image (BLOB of some sorts), I'm just looking to store "what and where".
What seems to be happening is if I try entering the contents of a shoot directory with several hundred images, when I hit input the screen changes, then instead of telling me how many were entered, it goes to a "418 unused" page saying
The server encountered an internal error or misconfiguration and was unable to complete your request.
I've been trying to narrow down which buffers to increase or variables like "max_allowed_packet", "max_input_vars"... still no luck. I've even tried comparing the phpinfo between the two servers to find out why one works and the other doesn't...
Here's what I'm doing... the listpage
<?php
// set page headers
$page_title = "Enter Images into Database";
include_once 'auth.php';
// get database connection
include_once 'config/fpaddb.php';
include_once 'objects/clients.php';
include_once 'objects/photoshoots.php';
include_once 'objects/images.php';
$database = new Database();
$db = $database->getConnection();
$colname_chk_Images = "-1";
if (isset($_GET['ShootId'])) {
$colname_chk_Images = $_GET['ShootId'];
}
$colname1_chk_Images = "NULL";
if (isset($_GET['ShootFolder'])) {
$colname1_chk_Images = $_GET['ShootFolder'];
}
$colname_get_Images = "-1";
if (isset($_SESSION['cID'])) {
$colname_get_Images = $_SESSION['cID'];
}
$entered=0; //check for already entered images
?>
<?php
$dirname=$_SESSION['cIFolder'];
$Clogin=$_SESSION['Clogin'];
$ClientID=$_SESSION['cID'];
$_SESSION['CURR_CLIENT_ID'] = $ClientID;
$maindir=$_GET['ShootFolder'];
$ShootId=$_GET['ShootId'];
$dir=$_SERVER['DOCUMENT_ROOT'].dirname($_SERVER['PHP_SELF'])."protect/clientfolders/".$Clogin."/users/".$Clogin."/images/".$maindir;
$_SESSION['dir']=$dir;
$dir2="/protect/clientfolders/".$Clogin."/users/".$Clogin."/images/".$maindir;
$dirt= "/phpThumb-master/";
$dirn= dirname($_SERVER['PHP_SELF']);
$filesArray=array_map('basename', glob($dir."/*.jpg"));
$lightbox_data= "FPAD_Lightbox";
$thumb = "$dir2/";
$notThumb = "$dir2/";
$ic = count($filesArray);
$_SESSION['SESS_TOTNUM'] = $ic;
$_SESSION['sID'] = $ShootId;
$sID = $_SESSION['sID'];
include_once 'header_a.php';
?>
<div class="container">
<?php
echo $_SESSION['SESS_TOTNUM']." images found ";
echo "for Shoot ID#: ".$_SESSION['sID']."<br>";
echo "*Note* - if input boxes come up GREEN, then images are already loaded into the database";
?>
<p>
<?php
$images1 = new Image($db);
$images1->ShootId = $colname_chk_Images;
$images1->directory = $colname1_chk_Images;
$images1->ClientID = $colname_get_Images;
$chk_Images = $images1->checkImages();
$get_Images = $images1->getImages();
$Images = array();
while ($row_get_Images = $get_Images->fetch(PDO::FETCH_ASSOC))
{
$Images[] = $row_get_Images['image_name'];
}
?></p>
<form method="POST" name="form1" id="form1" action="input.php">
<table id="clientshoots" class="table table-condensed table-bordered table-small">
<tr>
<th>image_id</th>
<th>image_name</th>
<th>image_path</th>
<th>image_path_root</th>
<th>image_size</th>
<th>directory</th>
<th width="auto">ShootId</th>
<th width="auto">ClientID</th>
<th>ClientName</th>
<th>login</th>
</tr>
<?php $ic=0;
for($i=0;$i<count($filesArray);$i++) {
$fileinfo = $filesArray[$i];
$fname=$dir."/".$fileinfo;
$fname2=$dir2."/".$fileinfo;
$size = filesize($fname);
$atime = date("F d, Y H:i:s", fileatime($fname));
$mtime= date("F d, Y H:i:s", filemtime($fname));
$perms=decoct(fileperms($fname) & 0777);
$type=filetype($fname);
$pth=realpath($fname);
$name=basename($fname);
$dn=dirname($fname2);
if (in_array($fileinfo, $Images)) {
$entered=1;
echo "<style type=\"text/css\">\n";
echo "input {\n";
echo "background-color:#00FF33;\n";
echo "}\n";
echo "</style>";
}
?>
<tr>
<td> </td>
<td><input type="text" name="image_name[]" value="<?php echo $fileinfo; ?>" readonly/></td>
<td><input type="text" name="image_path[]" value="<?php echo $dir; ?>" readonly/></td>
<td><input type="text" name="image_path_root[]" value="<?php echo $dir2; ?>" readonly/></td>
<td><input type="number" name="image_size[]" value="<?php echo $size; ?>" readonly/></td>
<td><input type="text" name="directory[]" value="<?php echo $maindir; ?>" readonly/></td>
<td><input type="number" name="ShootId[]" value="<?php echo $ShootId; ?>" readonly/></td>
<td><input type="number" name="ClientID[]" value="<?php echo $ClientID; ?>" readonly/></td>
<td><input type="text" name="ClientName[]" value="<?php echo $_SESSION['cName']; ?>" readonly/></td>
<td><input type="text" name="login[]" value="<?php echo $Clogin; ?>" readonly/></td>
</tr>
<?php next($filesArray);
$ic=$ic+1;
}
$_SESSION['SESS_IC'] = $ic;?>
</table>
<?php if ($entered == 1){
echo "Return";
} else {
echo "<input class=\"btn-primary\" style=\"background-color:\" id=\"Insert records\" type=\"submit\" value=\"Insert records\">";
}?>
<input type="hidden" name="MM_insert" value="form1">
<input type="hidden" name="sID" value="<?php echo $sID; ?>">
</form>
</div>
<br>
<!-- /container -->
<?php include 'footer_b.php'; ?>
and then the input.php page...
<?php
// set page headers
$page_title = "Enter Images into Database";
include_once 'auth.php';
// get database connection
include_once 'config/fpaddb.php';
include_once 'objects/clients.php';
include_once 'objects/photoshoots.php';
include_once 'objects/images.php';
include_once 'objects/ratings.php';
$database = new Database();
$db = $database->getConnection();
$sID = $_SESSION['sID'];
$ic = $_SESSION['SESS_IC'];
$ma = $_SESSION['SESS_CLIENT_MULTI'];
$gn = $_SESSION['SESS_CLIENT_GRPNO'];
$cID = $_SESSION['cID'];
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = filter_var(($str), FILTER_SANITIZE_STRING);
return ($str);
}
$image1 = new Image($db);
$count = count($_POST['image_name']);
$fileinfo = clean($_POST['image_name']);
//Check for duplicates
if($fileinfo != '') {
for($i=0;$i<$count;$i++) {
$fileinfo = clean($_POST['image_name'][$i]);
//echo $fileinfo;
$image1->image_name = $fileinfo;
$result = $image1->check4Dup();
if($result) {
if(count($result) > 0) {
$errmsg_arr[] = 'Image already entered into Database';
$errflag = true;
}
$result = NULL;
}
else {
die($e->getMessage());
}
next($count);
}
}
$image1->ic = $ic;
$num = $image1->create();
$colname_newImages = "-1";
if (isset($sID)) {
$colname_newImages = $sID;
}
$image1->ShootId = $sID;
$newImages = $image1->countOneShoot();
$row_newImages = $newImages->fetch(PDO::FETCH_ASSOC);
$totalRows_newImages = $newImages->rowCount();
$ic2 = $totalRows_newImages;
$_SESSION['SESS_TOTNUM_ENT'] = $ic2;
header("Location: rs_images.php");
include_once 'header_a.php';
?>
<div class="container">
<?php
echo "Success! Number of images entered is ".$ic2; ?>
<br><br>
<p><input name="Verify" type="button" value="Verify Inputs" onclick="MM_goToURL('parent','rs_images.php');return document.MM_returnValue"/></p>
</div>
<?php include 'footer_b.php'; ?>
And the Class file...
<?php
class Image{
// database connection and table name
private $dbh;
private $table_name = "images";
// object properties
public $image_id;
public $image_name;
public $image_path;
public $image_path_root;
public $image_size;
public $directory;
public $ShootId;
public $ClientID;
public $ClientName;
public $login;
public $ic;
public function __construct($db){
$this->dbh = $db;
}
// Clean Function
function clean($str){
$str = filter_var(($str), FILTER_SANITIZE_STRING);
return ($str);
}
// test function
function test(){
$ic = $this->ic;
$i=1;
$j=1;
foreach ($_POST['image_name'] as $row=>$iname)
{
$image_name = clean($iname);
$image_path = clean($_POST['image_path'][$row]);
$image_path_root = clean($_POST['image_path_root'][$row]);
$image_size = clean($_POST['image_size'][$row]);
$directory = clean($_POST['directory'][$row]);
$ShootId = clean($_POST['ShootId'][$row]);
$ClientID = clean($_POST['ClientID'][$row]);
$ClientName = clean($_POST['ClientName'][$row]);
$login = clean($_POST['login'][$row]);
$Clogin = $login."');";
$i=$i+1;
$j=$j+1;
$qry1st = "INSERT INTO `images` (image_name, image_path, image_path_root, image_size, directory, ShootId, ClientID, ClientName, login) VALUES ";
$sql_array = "('".$image_name."', '".$image_path."', '".$image_path_root."', ".$image_size.", '".$directory."', ".$ShootId.", ".$ClientID.", '".$ClientName."', '".$Clogin;
//$stmt = $this->dbh->prepare($qry1st.$sql_array);
//$stmt->execute();
echo $qry1st.$sql_array;
}
}
// create function
function create(){
$ic = $this->ic;
$qry1st = "INSERT INTO `images` (image_name, image_path, image_path_root, image_size, directory, ShootId, ClientID, ClientName, login) VALUES ";
$sql_array = array(); // This is where we'll queue up the rows
$queue_num = 50; // How many rows should be queued at once?
$i=1;
foreach ($_POST['image_name'] as $row=>$iname)
{
$image_name = clean($iname);
$image_path = clean($_POST['image_path'][$row]);
$image_path_root = clean($_POST['image_path_root'][$row]);
$image_size = clean($_POST['image_size'][$row]);
$directory = clean($_POST['directory'][$row]);
$ShootId = clean($_POST['ShootId'][$row]);
$ClientID = clean($_POST['ClientID'][$row]);
$ClientName = clean($_POST['ClientName'][$row]);
$login = clean($_POST['login'][$row]);
if ($i==($_SESSION['SESS_TOTNUM'])) {
$login_term = $login."');";
}
else
{
$login_term = $login."')";
$i=$i+1;
}
$sql_array[] = "('".$image_name."', '".$image_path."', '".$image_path_root."', ".$image_size.", '".$directory."', ".$ShootId.", ".$ClientID.", '".$ClientName."', '".$login_term;
// Add a new entry to the queue
$c=0;
if (count($sql_array) >= $queue_num)
{ // Reached the queue limit
$addImages = $this->dbh->query($qry1st . implode(', ', $sql_array)); // Insert those that are queued up
$addImages->execute();
$sql_array = array(); // Erase the queue
}//End if
}//end foreach
if (count($sql_array) > 0) // There are rows left over
{
$addImages = $this->dbh->query($qry1st . implode(', ', $sql_array));
$addImages->execute();
}
}
function checkImages(){
$query_chk_Images = "SELECT images.image_name FROM images WHERE ShootId = ? AND directory = ?";
$chk_Images = $this->dbh->prepare ($query_chk_Images);
$chk_Images->bindValue(1, $this->ShootId);
$chk_Images->bindValue(2, $this->directory);
$chk_Images->execute();
return $chk_Images;
}
// create function
function getImages(){
$query_get_Images = "SELECT * FROM images WHERE ClientID = ? ORDER BY image_name ASC";
$get_Images = $this->dbh->prepare ($query_get_Images);
$get_Images->bindValue(1, $this->ClientID);
$get_Images->execute();
return $get_Images;
}
// create function
function getImageID(){
$query_rsImageID = "SELECT * FROM images WHERE ShootId = ? ORDER BY image_id ASC";
$rsImageID = $this->dbh->prepare($query_rsImageID);
$rsImageID->bindValue(1, $this->ShootId);
$rsImageID->execute();
return $rsImageID;
}
// create function
function get_image_id(){
$q = "SELECT image_id FROM images WHERE ShootId = ? ORDER BY image_id ASC";
$stmt = $this->dbh->prepare($q);
$stmt->bindValue(1, $this->ShootId);
$stmt->execute();
return $stmt;
}
// create function
function countOneShoot(){
$query_newImages = "SELECT * FROM images WHERE ShootId = ?";
$newImages = $this->dbh->prepare($query_newImages);
$newImages->bindValue(1, $this->ShootId);
$newImages->execute();
return $newImages;
}
// create function
function check4Dup(){
$qry = "SELECT * FROM `images` WHERE image_name = ?";
$result = $this->dbh->prepare($qry);
$result->bindValue(1, $this->image_name);
$result->execute();
return $result;
}
}
I've striped out all the extra stuff I've tried, like entering the info one record at a time, binding the Values with colon prefixed field names instead of the ?'s. I've tried different loops. I think it comes down to trying to push too much through one query... but then why does it work on XAMPP and why was it working fine with PHP 5.2?
I appreciate any light that can be shed on this. This is my first ever post with regards to PHP, MySQL or anything site related, I've been learning this stuff as I go and had it 90% completed and debugged and when I put it online to do some real testing with the actual directories and client folders that's when I found out that between PHP 5.4 and 5.2, there have been a number of changes and I found myself rewriting almost every line to move up to either MySQLi or PDO/OOP. After doing a lot searching around the internet I've opted for the OOP approach and still need to rewrite even more of the code above to clean things up a ton, but right now I'm troubleshooting the INSERT failure which I have not been able to solve on my own or with the help of all the forums, posts and blogs I've read to date.

Delete image and copy from gallery

I have a gallery that I'm able to upload images with a title and a short description about the image. I store the images in a folder on my ftp and the data in a database. Here is a screen shot of the database.
I want to give my client a little more control over the gallery by allowing them to update the gallery and delete posts in the gallery. Right now I want to focus on the DELETING part.
I'm using the following code to try and delete the images/post by trying to select by id and delete.
When executing the delete script on the site I get no errors on the page or on my ftp, but the image does not delete.
The end result I'm looking for would be to have the row deleted from the table and the image deleted from the ftp.
I'm very new to php and know I need to learn much more about it, but if someone could help out I would appreciate it. I apologize for the code dump, but not sure how to ask the question without showing what I'm working with.
DELETE CODE:
<?php
//including the database connection file
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
//deleting the row from table
$result=mysql_query("DELETE FROM images where id='$id' limit 1;");
//redirecting to the display page (index.php in our case)
echo '<table align="center" width="100%" height="100%" border="0"><tr align="center" valign="center"><td><h2>Deleting Image</h2></td></tr></table>';
echo '<meta http-equiv="refresh" content="5;URL=/admin/modify-gallery.php">';
?>
This is the code I'm using to to access the image on the modify-gallery page
modify-gallery code:
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
/* be safe, not sorry */
foreach ($_REQUEST as $k => $v) {
$_REQUEST[$k] = mysql_real_escape_string($v);
}
/* take cat from url if exists */
$category = #$_REQUEST["category"] ? $_REQUEST["category"] : null;
$images = mysql_query(
$category ?
sprintf(
"SELECT * FROM images WHERE data_type = '%s'",
$category
) :
"SELECT * FROM images"
);
if ($images) {
$total = mysql_num_rows($images);
if ($total) {
$per = 12;
$page = #$_REQUEST["page"] ? $_REQUEST["page"] : 1;
$pages = ceil($total/$per);
}
mysql_free_result($images);
}
?>
and then this is used to display the images/posts and lists the delete and update button..(same page)
<div class="row">
<ul id="stage" class="portfolio-4column">
<?php
if ($category) {
$images = mysql_query(sprintf(
"SELECT * FROM images WHERE data_type = '%s' ORDER BY id DESC LIMIT %d, %d",
$category, ($page - 1) * $per, $per
));
} else $images = mysql_query(sprintf(
"SELECT * FROM images ORDER BY id DESC LIMIT %d, %d",
($page - 1) * $per, $per
));
while ($image=mysql_fetch_array($images))
{
?>
<li data-id="id-<?=$image["id"] ?>" data-type="<?=$image["data_type"] ?>">
<div class="grid_3 gallerybox-admin">
<div class="overallheight-admin">
<div class="gallerybox-admin"><a class="fancybox" rel="<?=$image["data_type"] ?>" href="http://<?php echo $_SERVER['SERVER_NAME']; ?>/images/gallery/<?=$image["file_name"] ?>" title="<?=$image["title"] ?>">
<img src="http://<?php echo $_SERVER['SERVER_NAME']; ?>/images/gallery/<?=$image["file_name"] ?>" alt="<?=$image["title"] ?>" class="max-img-border"></a></div>
<div class="galleryh"><?=$image["title"] ?></div>
<div class="galleryp"><?=$image["description"] ?></div>
</div>
<div class="grid_1"><h4 class="btn-green">Delete</h4></div>
<div class="grid_1"><h4 class="btn-green">Update</h4></div>
</div>
</li>
<?php
}
?>
</ul>
</div>
Code from Stack Overflow (Currently Using):
<?php
//including the database connection file
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
//Select image_name(if not known)
$img = mysql_query("Select file_name from images where id=\"$id\"");
$img_res = mysql_fetch_array($img);
$filename = $img_res[0];
unlink($_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $filename);
//deleting the row from table
$result=mysql_query("DELETE FROM images where id=\"$id\" limit 1;");
//redirecting to the display page
echo '<table align="center" width="100%" height="100%" border="0"><tr align="center" valign="center"><td><h2>Deleting Image</h2></td></tr></table>';
echo '<meta http-equiv="refresh" content="5;URL=/admin/modify-gallery.php">';
?>
fix this in delete button html, to pass the file name by the url
<h4 class="btn-green">Delete</h4></div>
In your remove.php
include("/connections/dbconnect.php");
$filename = isset($_GET['value']) ? $_GET['value'] : NULL;
if (!empty($filename)) {
$delete = unlink("images/gallery/" . $filename);
if($delete){
$result = mysql_query("DELETE FROM images where file_name="'. mysql_real_escape_string($filename)."' limit 1;")";
header("Location:succes_page.php");
}else{
header("Location:failure_page.php");
}
}else{
header("Location:failure_page.php");
}
side note try to update your mysql_* functions to PDO or mysqli
"The end result I'm looking for would be to have the row deleted from the table and the image deleted from the ftp."
the row deleted from the table ✓
But you still need to remove the actual file from your server to do so use unlink($fileName);
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
// Delete the file from the server
unlink($_SERVER['DOCUMENT_ROOT'] . "{Path Where Your Images stored}" . $row['file_name']);
//deleting the row from table
$result=mysql_query("DELETE FROM images where id='$id' limit 1;");
As you can see I used the $row['file_name'] to get the file name from you database (good to show us your table structure)
To delete a file from the ftp you should use
unlink(filename with complete path);
Complete Code:
//Change Delete code to following
<?php
//including the database connection file
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
//Select image_name(if not known)
$img = mysql_query("Select image_name(your column) from images where id=\"$id\"");
$img_res = mysql_fetch_array($img);
$filename = $img_res[0];
unlink("path to file".$filename);
//deleting the row from table
$result=mysql_query("DELETE FROM images where id=\"$id\" limit 1;");
//redirecting to the display page (index.php in our case)
echo '<table align="center" width="100%" height="100%" border="0"><tr align="center" valign="center"><td><h2>Deleting Image</h2></td></tr></table>';
echo '<meta http-equiv="refresh" content="5;URL=/admin/modify-gallery.php">';
?>

Categories