I have a problem in retrieving an image from a database. Here is the code that uploads the image to the database:
<form method="post" action="index2.php" enctype="multipart/form-data">
<input type="file" name="drimg2"/>
<input type="submit" name="submit2" value="Save"/>
</form>
<?php
if(isset($_POST['submit2'])) {
$con=mysql_connect("localhost","root","root");
mysql_select_db("test",$con);
$imgname1=$_FILES['drimg2']['name'];
echo $imgname1;
$imageextension1 = substr(strrchr($imgname1,'.'), 1);
if (($imageextension1!= "jpg") && ($imageextension1 != "jpeg") && ($imageextension1 != "gif")&& ($imageextension1 != "png")&& ($imageextension1 != "bmp")) {
die('Unknown extension. Only jpg, jpeg, and gif files are allowed. Please hit the back button on your browser and try again.');
}
if (($imageextension1= "jpg") && ($imageextension1= "jpeg") && ($imageextension1= "gif") && ($imageextension1 = "png") && ($imageextension1 = "bmp")) {
$query1=mysql_query("INSERT INTO store set image='$imgname1'");
$action = move_uploaded_file($_FILES['drimg2']['tmp_name'],"images/".$imgname1);
die('not Uploded');
}
}
?>
Now I want to retrieve all the images in the database; for this I am using the following code:
<?php
$query1="select * from store";
$fetch=mysql_query($query1);
while ($rows=mysql_fetch_array($fetch)) {
echo "<img src='images/".$rows['image']."' />";
}
?>
You should not be using the old mysql_* functions and use PDO or mysqli instead. Here is a much cleaner and securer way of doing what you want.
<?php
/**
* A Simple class to handle your database requests
* related to your image storage ect
*/
class image_model{
private $db;
function __construct($db){
$this->db = $db;
}
function add($img_name){
$sql = "INSERT INTO store (image) VALUES (:value)";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':value', $img_name, PDO::PARAM_STR);
$stmt->execute();
}
function get_all(){
$sql = "SELECT image FROM store";
return $this->db->query($sql)->fetchAll();
}
//Perhaps use in future
function get_image($id){
$sql = "SELECT image FROM store WHERE id=:id";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
return $result->fetchAll();
}
}
//Connect safely to your database...
try{
$db = new PDO("mysql:host=localhost;dbname=test", 'root', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
die('Cannot connect to mySQL server. Details:'.$e->getMessage());
}
//Create an instance of the image model above
$img_model = new image_model($db);
//Boom...Handle the upload
if($_SERVER['REQUEST_METHOD']=='POST'){
if ($_FILES["img"]["error"] > 0){
echo "Error: ".$_FILES["img"]["error"]."<br />";
}else{
$img = getimagesize($_FILES["img"]["tmp_name"]);
$allowed = array('image/jpeg','image/gif','image/png','image/bmp');
//Width and height must be more then 0 pixles and mime must be in allowed array
if($img[0] > 0 && $img[1] > 0 && in_array($img['mime'],$allowed)){
if(is_uploaded_file($_FILES["img"]["tmp_name"])){
//Clean image name
$img_name = preg_replace('/[^a-zA-Z0-9.-]/s', '_', basename($_FILES["img"]["name"]));
//move image to folder
move_uploaded_file($_FILES["img"]["tmp_name"],"images/".$img_name);
//Add image to db using a method from the image model
$img_model->add($img_name);
}
}else{
echo "Error: Unknown extension. Only jpg, bmp and gif files are allowed. Please hit the back button on your browser and try again.<br />";
}
}
}
//Your form
?>
<h1>Upload image</h1>
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="img"/>
<input type="submit" name="submit" value="Save"/>
</form>
<?php
//Access your image model in a simple way and get all images
foreach($img_model->get_all() as $row){
echo '<img src="images/'.$row['image'].'" /><br />';
}
?>
Refer this link,
Hope this will help.
Change retrieval of image code to following,
$content = $row['image'];
header('Content-type: image/jpg');
echo $content;
try this I've tested this code and made some modifications.
<form method="post" action="index2.php" enctype="multipart/form-data">
<input type="file" name="drimg2"/>
<input type="submit" name="submit2" value="Save"/>
</form>
<?php
if(isset($_POST['submit2'])) {
$con=mysql_connect("localhost","root","root");
mysql_select_db("test",$con);
$imgname1=$_FILES['drimg2']['name'];
//echo $imgname1;
$imageextension1 = substr(strrchr($imgname1,'.'), 1);
//echo '<pre>';print_r($imageextension1);echo '</pre>';die('Call');
if (($imageextension1!= "jpg") && ($imageextension1 != "jpeg") && ($imageextension1 != "gif")&& ($imageextension1 != "png")&& ($imageextension1 != "bmp")) {
die('Unknown extension. Only jpg, jpeg, and gif files are allowed. Please hit the back button on your browser and try again.');
} else {
//if (($imageextension1 == "jpg") && ($imageextension1 == "jpeg") && ($imageextension1 == "gif") && ($imageextension1 == "png") && ($imageextension1 = "bmp")) {
if(move_uploaded_file($_FILES['drimg2']['tmp_name'],"images/".$imgname1)) {
$query1=mysql_query("INSERT INTO fileurl(filename) VALUES('".$imgname1."')"); //fileurl is table name and filename is field name
if($query1) {
echo "Data inserted";
} else {
echo "Data not inserted";
}
} else {
echo "Error occured while trying to upload image";
}
//$action = ;
//die('not Uploded');
}
}
?>
and for fetching images try this
$query = "SELECT * FROM fileurl";
$fetch = mysql_query($query);
while($rows = mysql_fetch_array($fetch)) {
echo "<img src='images/".$rows['filename']."' />";
}
if your image format not matched it will close the program automatically otherwise it'll jump to the else condition and upload the image and then insert the name of file into the database.
Related
I still have the error 2 days after. Help...
I have an error with picture upload in my code. The file upload works perfectly when i remove anything image related but fails once i add anything image related.
I get 2 errors
"Sorry, there was a problem uploading your file." and
"Problem uploading item". I have no idea why...
I'll post the section i have the problem with.
if((($_FILES["pic"]["type"] != "image/jpg")
|| ($_FILES["pic"]["type"] != "image/jpeg")
|| ($_FILES["pic"]["type"] != "image/png")
|| ($_FILES["pic"]["type"] != "image/pjpeg"))
&& ($_FILES["pic"]["size"] > 1000000))
{
$_SESSION['itemerror'][] = "Pic must be jpg, jpeg, png or pjpeg and must be less than 1mb";
}
//final disposition
if (count($_SESSION['itemerror']) > 0) {
die(header("Location: postitem.php"));
} else {
if(registerItem($_POST)) {
unset($_SESSION['formAttempt']);
$_SESSION['itemsuccess'][] = "Successfully Uploaded";
die(header("Location: postitem.php"));
} else {
error_log("Problem uploading item: {$_POST['name']}");
$_SESSION['itemerror'][] = "Problem uploading item";
die(header("Location: upload.php"));
}
}
function registerItem($userData) {
$mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB);
if ($mysqli->connect_errno) {
error_log("Cannot connect to MySQL: " . $mysqli->connect_error);
return false;
}
$target = "img/";
$target = $target . basename( $_FILES['pic']['name']);
$pic=($_FILES['pic']['name']);
$poster = htmlspecialchars($mysqli->real_escape_string($_POST['user']));
$itemcategory = htmlspecialchars($mysqli->real_escape_string($_POST['category']));
$itemname = htmlspecialchars($mysqli->real_escape_string($_POST['name']));
$itemdescription = htmlspecialchars($mysqli->real_escape_string($_POST['description']));
$itemprice = htmlspecialchars($mysqli->real_escape_string($_POST['price']));
$itemlocation = htmlspecialchars($mysqli->real_escape_string($_POST['addr']));
$itemcity = htmlspecialchars($mysqli->real_escape_string($_POST['city']));
$itemstate = htmlspecialchars($mysqli->real_escape_string($_POST['state']));
$itemphone = htmlspecialchars($mysqli->real_escape_string($_POST['phone']));
$itemnegotiate = htmlspecialchars($mysqli->real_escape_string($_POST['negotiate']));
if(move_uploaded_file($_FILES['pic']['tmp_name'],$target)){
$query = "INSERT INTO Product
(category,name,upload_date,user,
description,price,location,city,
state,phone,negotiatable,pic_link)" .
" VALUES ('{$itemcategory}','{$itemname}',NOW(),'{$poster}',
'{$itemdescription}','{$itemprice}','{$itemlocation}'" .
",'{$itemcity}','{$itemstate}','{$itemphone}','{$itemnegotiate}', '{$pic}')";
if ($mysqli->query($query)) {
$itemname = $mysqli->insert_itemname;
error_log("Inserted {$itemname} as ID {$id}");
return true;
} else {
error_log("Problem inserting {$query}");
return false;
}
} else {
$_SESSION['itemerror'][] = "Sorry, there was a problem uploading your file.";
}
}
The form contains this:
<form id="userForm" method="POST" action="upload.php">
And this for the picture input:
<label for="pic">Pictures: </label>
<input class="input100" type="file" id="pic" name="pic">
Add the attribute enctype="multipart/form-data" to your <form>
Like this
<form id="userForm" method="POST" action="upload.php" enctype="multipart/form-data">
I do not know if that will solve your problem, but it will probably help you.
It seems to me that it's mandatory for an upload form.
I am new to php. I made a simple upload form in php. This is my code.
<html><head></head>
<body>
<form method="post" action="" enctype="multipart/form-data">
Upload File:
<input type="file" name="upload" /><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
<?php
include("config.php");
if(isset($_POST['submit']) )
{
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
if ($_FILES['upload']['name'] == 0 ){
echo "<br><br> New record created successfully";
}
else {
$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;
if ($con->query($query) === TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
$con->close();
}
?>
It works fine. But if I press the submit with no files attached, it displays the error, Warning: file_get_contents(): Filename cannot be empty in C:\xampp\htdocs\contractdb\filetest.php on line 20 .
I want uploading files to be optional because not every user has the files to attach. I also want the user to download the files after uploading without removing file_get_contents($_FILES['upload']['tmp_name']).
How do I do this?
Your check should take in place before calling file_get_content() so it does not throw an error and you only call the function if file input is not empty:
if(isset($_POST['submit']) ) {
if ($_FILES['upload']['size'] != 0 ) {
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']
['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;
if ($con->query($query) == TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
else {
echo 'error: empty file';
}
}
Try this:
if (isset($_POST['submit']) & ($_FILES['upload']['name']!=''))
{
// Statement
}
I have written some codes to collect images, re-size, upload to two different folders and store the new name in a mysql database. Every other aspect of the code is working. The only issue i am having is that, the new name given to the image is not being stored in the datatbase. What i am getting is just a single digit. E.g rather than have the name of file uploaded as 1234_12345.jpg stored in the database, the file name stored is just say 1 or 3 etc.
Below is my form:
<form method="POST" id="adimageadd" action="<?php echo $editFormAction; ?>" name="adimageadd" enctype="multipart/form-data">
<div class="h1">Select Album:</div>
<select class="input-field-login2" id="albumselect" name="albumselect" required type="text" tabindex="1">
<option value="">Please Select</option>
<?php foreach ($result_album as $rs) { ?>
<option value="<?php echo $rs["alID"]; ?>"><?php echo $rs["alTitle"]; ?></option>
<?php } ?>
</select>
<input type="hidden" name="MAX_FILE_SIZE" value="" />
<input name="photo[]" type="file" required id="photo" size="26" multiple='multiple'/>
<button name="login" type="submit" id="login_submit" tabindex="3">Add Images</button>
<input type="hidden" name="form_insert" value="adimageadd">
</form>
And the php code is:
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
define ("MAX_SIZE","2048");
$errors=0;
$query_album = "SELECT alID, alTitle, alImage, alDesc FROM galbum ORDER BY alID DESC";
$result_album = mysqli_query($connKcla, $query_album);
$row_album = mysqli_fetch_assoc($result_album);
$totalRows_album = mysqli_num_rows($result_album);
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["form_insert"])) && ($_POST["form_insert"] == "adimageadd")) {
//get form details and check for sql injections and disable them
$albumRef = mysqli_real_escape_string($connKcla, $_POST['albumselect']);
$image = $_FILES["photo"]["name"];
$uploadedfile = $_FILES['photo']['tmp_name'];
$img = count($image);
for ($i = 0; $i < $img; $i++) {
if ($image){
$filename = mysqli_real_escape_string($connKcla, $image[$i]);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo ' Unknown Image extension ';
$errors=1;
}
else
{
$size=filesize($_FILES['photo']['tmp_name'][$i]);
if ($size > MAX_SIZE*1024)
{
echo "Your image has exceeded the size limit of 2Mb. Click the back button on your browser to re-enter the right size of image";
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['photo']['tmp_name'][$i];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['photo']['tmp_name'][$i];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=760;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$thumbnewwidth=250;
$thumbnewheight=($height/$width)*$thumbnewwidth;
$thumbtmp=imagecreatetruecolor($thumbnewwidth,$thumbnewheight);
imagecopyresampled($thumbtmp,$src,0,0,0,0,$thumbnewwidth,$thumbnewheight,$width,$height);
$set['photo'] = $image[$i];
$kaboom = explode(".", $image[$i]);
$pixExt = end($kaboom);
$photo = rand()."_".time().".".$pixExt;
$target = "../gallery/images/". $photo;
$thumbtarget = "../gallery/images/thumbs/". $photo;
imagejpeg($tmp,$target,100);
imagejpeg($thumbtmp,$thumbtarget,75);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($thumbtmp);
}
}
$stmt = $connKcla->prepare("INSERT INTO gimage (imImage, albumRef) VALUES ($photo[$i], $albumRef)");
$results = $stmt->execute();
$stmt->close();
if($results){
$updateGoTo = "confirm.php";
if (isset($_SERVER['QUERY_STRING'])) {
$updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
$updateGoTo .= $_SERVER['QUERY_STRING'];
}
header("Location: ". $updateGoTo);
}else{
header("Location: error.php");
}
}
}
Please any help would be much appreciated.
This creates a string:
$photo = rand()."_".time().".".$pixExt;
This gets one character from that string:
$photo[$i]
Which you're storing in your database:
$stmt = $connKcla->prepare("INSERT INTO gimage (imImage, albumRef) VALUES ($photo[$i], $albumRef)");
If you want to store the whole string, just use the string itself and not the index of a specific character:
$stmt = $connKcla->prepare("INSERT INTO gimage (imImage, albumRef) VALUES ($photo, $albumRef)");
//^-- here
Additionally, you should probably start looking into using query parameters and prepared statements. While this code may coincidentally not currently be open to SQL injection if none of the input is from users, it's still difficult to guarantee that. And not being open to SQL injection is a good habit to get into in general.
Problem solved. I just changed the value part of the query from:
$stmt = $connKcla->prepare("INSERT INTO gimage (imImage, albumRef) VALUES ($photo[$i], $albumRef)");
to
$stmt = $connKcla->prepare("INSERT INTO gimage (imImage, albumRef) VALUES ('$photo', '$albumRef')");
Hi I am trying the data like title,Description and image.If i give only title and description without adding image the data should be inserted into database.But if I am trying that getting error.Here is my error and code:
error: error while uploading
my code
$title=$_POST['blog_title'];
$result = str_replace(" ", "-", $title);
$description=$_POST['blog_description'];
$name=$_FILES["image"]["name"];
$type=$_FILES["image"]["type"];
$size=$_FILES["image"]["size"];
$temp=$_FILES["image"]["tmp_name"];
$error=$_FILES["image"]["error"];
if($error>0)
die("error while uploading");
else
{
if($type == "image/png" || $type == "image/jpg"|| $type == "image/jpeg" || $type == "image/svg" || $type == "image/jpe" )
{
move_uploaded_file($temp,"upload/".$name);
$sql=mysql_query("INSERT INTO blogs(image,blog_title,blog_description)values('$name','$result','$description')");
echo "upload complete";
session_start();
header("Location:blogimage.php");
}
else
{
echo "failure";
}
Html Code
<form method="POST" action="blogs.php" enctype="multipart/form-data">
<div>
<label for="title">Title</label>
<input type="text" name="blog_title" value="">
</div>
<div>
<label for="image">IMAGE</label>
<input type="file" name="image">
</div>
<div>
<label for="blog_description">Description</label>
<textarea name="blog_description" class="text" style="width:50%;"> </textarea>
</div>
<input type="submit" value="Submit"/>
</form>
According to your code if you are not uploading the image, value of $error becomes 4. So your if() condition is getting executed. So remove your if condition.
if ($name = $_FILES["image"]["name"] != '') {
if ($type == "image/png" || $type == "image/jpg" || $type == "image/jpeg" || $type == "image/svg" || $type == "image/jpe") {
move_uploaded_file($temp, "upload/" . $name);
$sql = mysql_query("INSERT INTO blogs(image,blog_title,blog_description)values('$name','$result','$description')");
echo "upload complete";
}else{
echo "File type not supported.";
}
session_start();
header("Location:blogimage.php");
} else {
$sql = mysql_query("INSERT INTO blogs(blog_title,blog_description)values('$result','$description')");
echo "upload complete";
session_start();
header("Location:blogimage.php");
}
First of all, start session at the very top of your PHP script, like this:
<?php
session_start();
?>
And now comes your issue. First use is_uploaded_file() function to check whether a file is uploaded or not, and then process your form accordingly.
So your code should be like this:
$title=$_POST['blog_title'];
$result = str_replace(" ", "-", $title);
$description=$_POST['blog_description'];
if(is_uploaded_file($_FILES['image']['tmp_name'])){
$name=$_FILES["image"]["name"];
$type=$_FILES["image"]["type"];
$size=$_FILES["image"]["size"];
$temp=$_FILES["image"]["tmp_name"];
$error=$_FILES["image"]["error"];
$ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
if($error > 0){
die("error while uploading");
}else{
$permissible_extension = array("png", "jpg", "jpeg", "svg", "jpe");
if(in_array($ext, $permissible_extension)){
if(move_uploaded_file($temp,"upload/".$name)){
$sql = mysql_query("INSERT INTO blogs(image,blog_title,blog_description)values('$name','$result','$description')");
if($sql){
header("Location:blogimage.php");
exit();
}else{
echo "Insertion failed";
}
}else{
echo "File couldn't be uploaded";
}
}else{
echo "Invalid format";
}
}
}else{
$sql = mysql_query("INSERT INTO blogs(blog_title,blog_description)values('$result','$description')");
if($sql){
header("Location:blogimage.php");
exit();
}else{
echo "Insertion failed";
}
}
Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.
You have to use like below:
...
if($type == "image/png" || $type == "image/jpg"|| $type == "image/jpeg" || $type == "image/svg" || $type == "image/jpe" )
{
move_uploaded_file($temp,"upload/".$name);
$sql=mysql_query("INSERT INTO blogs(image,blog_title,blog_description)values('$name','$result','$description')");
} else {
$sql=mysql_query("INSERT INTO blogs(blog_title,blog_description)values('$result','$description')");
}
session_start();
header("Location:blogimage.php");
...
I am using mysqli_query with your code, because mysql_* is deprecated:
Modified Code:
<?php
$link = mysqli_connect("localhost", "root", "", "yourDb");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$title=$_POST['blog_title'];
$result = str_replace(" ", "-", $title);
$description=$_POST['blog_description'];
$name = "";
$failure = "";
if(isset($_FILES["image"]["name"])){
$name=$_FILES["image"]["name"];
$type=$_FILES["image"]["type"];
$size=$_FILES["image"]["size"];
$temp=$_FILES["image"]["tmp_name"];
$error=$_FILES["image"]["error"];
if($error>0){
$name = "";
}
else{
if($type == "image/png" || $type == "image/jpg"|| $type == "image/jpeg" || $type == "image/svg" || $type == "image/jpe" )
{
move_uploaded_file($temp,"upload/".$name);
}
}
}
$sql = mysqli_query($link,"INSERT INTO blogs (image,blog_title,blog_description)
values('$name','$result','$description')");
if($sql){
//echo "upload complete";
session_start();
header("Location:blogimage.php");
die();
}
else{
echo 'failure';
}
?>
Explanation:
I am checking if if $_FILES["image"]["name"] is set than execute the file upload code.
further more if $error is not equal to 0 use move_uploaded_file()
Query will run in default either file empty or not, if empty than use $name as empty else use file name.
From PHP Manual:
mysqli::query -- mysqli_query — Performs a query on the database
Note that, its a procedural structure of mysqli_* extension, ist param of mysqli_query should be your connection identifier and second param should be your MYSQL Statement.
You have to make your fields and values dynamic :
Try this :
$_POST = array('image'=>'','blog_title'=>'yes','blog_description'=>'nothing');
foreach ($_POST as $key => $value) {
if(!empty($value)){
$fields .= $key.',';
$values .= "'".$value."'".',';
}
}
$fields = substr($fields, 0, -1);
$values = substr($values, 0, -1);
echo "INSERT INTO blogs($fields)values($values)";
I wonder whether someone may be able to help me please.
I've put together this form which, if you scroll to the bottom of the page, has multiple submission buttons. i.e 'Submit', 'Deleted selected image' and 'View Selected Image'.
I posted a query on this site yesterday here, about about how to go about dealing with multiple 'submission' buttons and received some great advice.
I've tried to implement the advice I was given, but I just can't seem to get this to work. As the guidance suggested, I've added a name to each button and tried to call that through the PHP script, but all that happens is the page refreshes as if submitting the whole page, rather, than for example, being able to view the selected file.
I just wondered whether someone could perhaps take a look at this please and let me know where I'm going wrong.
Please find my PHP code & Form script below
<?php
$db_host = 'host';
$db_user = 'username';
$db_pwd = 'password';
$database = 'databasename';
$table = 'images';
// use the same name as SQL table
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
return mysql_real_escape_string($s);
}
// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (!isset($_POST["action"]))
{
// cleaning title field
$title = trim(sql_safe($_POST['title']));
if ($title == '') // if title is not set
$title = '(No Title Provided)';// use (empty title) string
//print_r($_FILES);exit;
if($_FILES["photo"]["error"] >= 4) {
$msg = '<b>Error!</b> - You <b> must </b> select a file before clicking the <b> "Upload This Image" </b> button. Please try again.';
}
else
if (isset($_FILES['photo']))
{
list($width, $height, $imtype, $attr) = getimagesize($_FILES['photo']['tmp_name']);
if ($imtype == 3) // cheking image type
$ext="png"; // to use it later in HTTP headers
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = '<b> Error! </b> - The image that you attempted to upload is not in the correct format. The file format <b> must </b> be one of the following: <b> "gif", "jpeg" </b> or <b> "png" </b>. Please try again.';
if($_FILES["photo"]["size"]/1150000 >= 1) {
$msg = '<b> Error! </b> - The file that you are attempting to upload is greater than the prescribed <b> 1MB </b> limit. Please try again.';
}
if (!isset($msg)) // If there was no error
{
$data = file_get_contents($_FILES['photo']['tmp_name']);
$data = mysql_real_escape_string($data);
// Preparing data to be used in MySQL query
mysql_query("INSERT INTO {$table}
SET ext='$ext', title='$title',
data='$data'");
$msg = '<b> Success! </b> - Your image has been uploaded';
}
}
elseif (isset($_GET['title'])) // isset(..title) needed
$msg = 'Error: file not loaded';// to make sure we've using
// upload form, not form
// for deletion
if (isset($_POST['deleteimage'])) // If used selected some photo to delete
{ // in 'uploaded images form';
$imageid = intval($_POST['del']);
mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
$msg = 'The image which you selected has now been deleted!';
}
if (isset($_POST['viewimage'])) // If used selected some photo to delete
{ // in 'uploaded images form';
$imageid = intval($_POST['view']);
mysql_query("SELECT ext, data FROM {$table} WHERE imageid=$imageid");
if(mysql_num_rows($result) == 1)
{
$image = $row['myimage'];
header("Content-type: image/gif"); // or whatever
print $image;
exit;
}
}
}
else
{
$imageid = intval($_POST['del']);
if ($_POST["action"] == "view")
{
$result = mysql_query("SELECT ext, UNIX_TIMESTAMP(imagetime), data
FROM {$table}
WHERE imageid=$imageid LIMIT 1");
if (mysql_num_rows($result) == 0)
die('no image');
list($ext, $imagetime, $data) = mysql_fetch_row($result);
$send_304 = false;
if (php_sapi_name() == 'apache') {
// if our web server is apache
// we get check HTTP
// If-Modified-Since header
// and do not send image
// if there is a cached version
$ar = apache_request_headers();
if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists
($ar['If-Modified-Since'] != '') && // not empty
(strtotime($ar['If-Modified-Since']) >= $imagetime)) // and grater than
$send_304 = true; // imagetime
}
if ($send_304)
{
// Sending 304 response to browser
// "Browser, your cached version of image is OK
// we're not sending anything new to you"
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304);
exit(); // bye-bye
}
// outputing HTTP headers
header('Content-Length: '.strlen($data));
header("Content-type: image/{$ext}");
// outputing image
echo $data;
exit();
}
else if ($_POST["action"] == "delete")
{
$imageid = intval($_POST['del']);
mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
$msg = 'The image which you selected has now been deleted!';
}
}
}
?>
<form action="<?=$PHP_SELF?>" method="post" enctype="multipart/form-data">
<div align="left">
<!-- This form is used for image deletion -->
<?php
$result = mysql_query("SELECT imageid, imagetime, title FROM {$table} ORDER BY imageid DESC");
if (mysql_num_rows($result) == 0) // table is empty
echo '<ul><li>You have no images loaded</li></ul>';
else
{
echo '<ul>';
while(list($imageid, $imagetime, $title) = mysql_fetch_row($result))
{
// outputing list
echo "<li><input type='radio' name='del' title, value='{$imageid}' />";
echo " <small>{$title}</small>  ";
echo "<small>{$imagetime}</small></li>";
}
echo '</ul>';
echo '<input type="submit" value="Delete Selected Image" onclick="document.getElementById(\'action\').value=\'delete\'" />';
echo '<input type="submit" value="View Selected Image" onclick="document.getElementById(\'action\').value=\'view\'" />';
}
?>
<input type="hidden" name="action" id="action" />
</div>
</form>
Many thanks and kind regards
Where you're checking the $_POST action, you need to do this:
if ($_POST["viewimage"] == "View Selected Image") { // Do stuff }
if ($_POST["deleteimage"] == "Delete Selected Image") { // Do stuff }
Basically, you need to check $_POST['name'] == 'value'