Mysqli 2 records being created with one insert - php

I am using the following form to create a photo album, it submits the data to a processing script which then deals with the files and enters data into the database.
THIS IS THE SUBMIT FORM :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Create New Album</title>
</head>
<body>
<p>Create New Album</p>
<form action="createnewalbumsubmit.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<input type="hidden" value="<?php echo substr(md5(time() * rand()),0,10); ?>" name="albumid" id="albumid" />
<input type="hidden" value="<?php echo date("Y-m-d"); ?>" name="datecreated" id="datecreated" />
<input type="hidden" value="yes" name="isalbum" id="isalbum" />
<p>
<label for="albumname">Album Name</label>
<input type="text" name="albumname" id="albumname" />
</p>
<p>
<label for="albumthumbnail">Album Thumbnail Image</label>
<input type="file" name="albumthumbnail" id="albumthumbnail" />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Submit" />
</p>
</form>
</body>
</html>
THIS IS THE DATA PROCESSING SCRIPT, IT IS USING THE VEROT UPLOAD CLASS FOR DEALING WITH THE UPLOADED FILE AND THEN MYSQLI TO ADD DETAILS TO THE DATABASE :
<?php include("connect.php"); ?>
<?php
// Posted Data
if(isset($_POST['albumid'])){
$albumid = $_POST['albumid'];};
if(isset($_POST['datecreated'])){
$datecreated = $_POST['datecreated'];};
if(isset($_POST['isalbum'])){
$isalbum = $_POST['isalbum'];};
if(isset($_POST['albumname'])){
$albumname = $_POST['albumname'];};
//
require_once 'uploadclass/class.upload.php';
$file = new Upload($_FILES['albumthumbnail']);
if ($file->uploaded) {
// save uploaded image with a new name,
// resized to 100px wide
$albumthumbnail = substr(md5(time() * rand()),0,10);
$file->file_new_name_body = $albumthumbnail;
$file->image_resize = true;
$file->image_convert = 'jpg';
$file->image_x = 100;
$file->image_ratio_y = true;
$file->Process('albums/'.$albumid.'/thumbnail/');
$filename = $file->file_dst_name;
if ($file->processed) {
echo 'image renamed, resized x=100
and converted to jpg';
$file->Clean();
} else {
echo 'error : ' . $file->error;
}
}
mysqli_query($db,"INSERT INTO albums (`albumid`,`datecreated`,`isalbum`,`albumname`,`albumthumbnail`) VALUES ('$albumid','$datecreated','$isalbum','$albumname','$filename')");
?>
The problem I am having is that when I create a new record TWO records are being created in the database, one blank record with nothing at all in it and one valid record with all of the details of the added album in it.

It's because you're not checking if the form is being posted. Each time you land on the page it will run:
mysqli_query($db, "INSERT INTO albums (`albumid`,`datecreated`,`isalbum`,`albumname`,`albumthumbnail`) VALUES ('$albumid','$datecreated','$isalbum','$albumname','$filename')");
This is why you're getting a blank record. You need to surround your submit code with if (!empty($_POST)) { } as such:
<?php
include ("connect.php");
if (!empty($_POST)) {
// Posted Data
if (isset($_POST['albumid'])) {
$albumid = $_POST['albumid'];
};
if (isset($_POST['datecreated'])) {
$datecreated = $_POST['datecreated'];
};
if (isset($_POST['isalbum'])) {
$isalbum = $_POST['isalbum'];
};
if (isset($_POST['albumname'])) {
$albumname = $_POST['albumname'];
};
//
require_once 'uploadclass/class.upload.php';
$file = new Upload($_FILES['albumthumbnail']);
if ($file -> uploaded) {
// save uploaded image with a new name,
// resized to 100px wide
$albumthumbnail = substr(md5(time() * rand()), 0, 10);
$file -> file_new_name_body = $albumthumbnail;
$file -> image_resize = true;
$file -> image_convert = 'jpg';
$file -> image_x = 100;
$file -> image_ratio_y = true;
$file -> Process('albums/' . $albumid . '/thumbnail/');
$filename = $file -> file_dst_name;
if ($file -> processed) {
echo 'image renamed, resized x=100
and converted to jpg';
$file -> Clean();
} else {
echo 'error : ' . $file -> error;
}
}
mysqli_query($db, "INSERT INTO albums (`albumid`,`datecreated`,`isalbum`,`albumname`,`albumthumbnail`) VALUES ('$albumid','$datecreated','$isalbum','$albumname','$filename')");
}
?>

Related

How to solve broken image displayed using php after upload to database

I try upload image to mysql database and display it along with the description of image using php. After i upload the image and display it , a broken image was displayed but the description of the image was displayed without any error. How can I solve this problem ? Appreciate your help
<?php
$msg = "";
//if upload button is pressed
if(isset($_POST['upload']))
{
// the path to store the uploaded image
$target = "images/".basename($_FILES['image']['name']);
// connect to database
$db = mysqli_connect("localhost","root","","product");
// Get all the submitted data from the form
$image = $_FILES['image']['name'];
$text = $_POST['text'];
$sql = "INSERT INTO product_list (image, text) VALUES ('$image','$text')";
mysqli_query($db,$sql); // stores the submitted data into the database table : product_list
// move uploaded image to the folder : image
if (move_uploaded_file($_FILES['image']['tmp_name'],$target))
{
$msg = "Image and text uploaded successfully";
}else
{
$msg = "There was a problem uploading image";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload With Description</title>
<link rel="stylesheet" type="text/css" href="formstyle.css">
</head>
<body>
<div id="content">
<?php
$db = mysqli_connect("localhost","root","","product");
$sql = "SELECT * FROM product_list";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result))
{
echo "<div id='img_div'>";
echo "<img src='".$row['image']."'>";
echo "<p>".$row['text']."</p>";
echo "</div>";
}
?>
<form method="post" action="try.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea name="text" cols="40" rows="4" placeholder="Details of product"></textarea>
</div>
<div>
<input type="submit" name="upload" value="Upload Image">
</div>
</form>
</div>
</body>
</html>
This is my result :
You are storing it in the DB without the images directory. You either need to store it with that, or always remember to call it that way in your image calls.
echo "<img src='images/".$row['image']."'>";
or make your the record you are writing the same as the filesystem location.
$image = 'images/' . $_FILES['image']['name'];
Note you are open to SQL injections and file inclusion injections with this code.
try this
<?php
$msg = "";
//if upload button is pressed
if(isset($_POST['upload']))
{
// the path to store the uploaded image
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$target_path = $destination_path . basename( $_FILES["image"]["name"]);
// connect to database
$db = mysqli_connect("localhost","root","","product");
// Get all the submitted data from the form
$image = $_FILES['image']['name'];
$text = $_POST['text'];
$sql = "INSERT INTO product_list (image, text) VALUES ('$image','$text')";
mysqli_query($db,$sql); // stores the submitted data into the database table : product_list
//#move_uploaded_file($_FILES['image']['tmp_name'], $target_path)
// move uploaded image to the folder : image
if (move_uploaded_file($_FILES['image']['tmp_name'],$target_path))
{
$msg = "Image and text uploaded successfully";
}else
{
$msg = "There was a problem uploading image";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload With Description</title>
<link rel="stylesheet" type="text/css" href="formstyle.css">
</head>
<body>
<div id="content">
<?php
$db = mysqli_connect("localhost","root","","product");
$sql = "SELECT * FROM product_list";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result))
{
echo "<div id='img_div'>";
echo "<img src='".$row['image']."'>";
echo "<p>".$row['text']."</p>";
echo "</div>";
}
?>
<form method="post" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea name="text" cols="40" rows="4" placeholder="Details of product"></textarea>
</div>
<div>
<input type="submit" name="upload" value="Upload Image">
</div>
</form>
</div>
</body>
</html>

PHP create folder inside ($_POST)

I need to upload the image to a server and store to the directory created by PHP using current timestamp. Below is the relevant part of the code, but not working as expected, it's not creating a folder as well it's not printing to the console. What could be the issue?
Edit:
Modified php based on below comment
upload.php
<?php
//get unique id
$up_id = uniqid();
?>
<?php
//process the forms and upload the files
if ($_POST) {
//specify folder for file upload
$user = "user";
//console.log("debug.......");
echo "debug.......";
if (!file_exists("/var/www/Scan")) {
mkdir("/var/www/Scan", 0777, true);
}
$folderName = date("Y-m-d") . "_" . date("h_i_sa") . "_" . $user;
if (!file_exists("/var/www/Scan/$folderName")) {
mkdir("/var/www/Scan/$folderName", 0777, true);
}
$folder = "/var/www/Scan/$folderName";
//specify redirect URL
$redirect = "upload.php?success";
//upload the file
move_uploaded_file($_FILES["file"]["tmp_name"], "$folder" . $_FILES["file"]["name"]);
//do whatever else needs to be done (insert information into database, etc...)
//redirect user
header('Location: '.$redirect); die;
}
//
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Upload your file</title>
<!--Progress Bar and iframe Styling-->
<link href="style_progress.css" rel="stylesheet" type="text/css" />
<!--Get jQuery-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.js" type="text/javascript"></script>
<!--display bar only if file is chosen-->
<script>
$(document).ready(function() {
//
//show the progress bar only if a file field was clicked
var show_bar = 0;
$('input[type="file"]').click(function(){
show_bar = 1;
});
//show iframe on form submit
$("#form1").submit(function(){
if (show_bar === 1) {
$('#upload_frame').show();
function set () {
$('#upload_frame').attr('src','upload_frame.php?up_id=<?php echo $up_id; ?>');
}
setTimeout(set);
}
//document.getElementById("message").innerHTML = "";
});
//
});
</script>
</head>
<body>
<div id="outPopUp">
<h1 >Upload your file </h1>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<br />
<br />
<!--Choose a file to upload<br />-->
<!--APC hidden field-->
<input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<?php echo $up_id; ?>"/>
<!---->
<!-- <input name="file" type="file" id="file" size="30"/>-->
<label class="custom-file-upload">
<input name="file" type="file" id="file" onclick="myFunction()" />
Choose Video
</label>
<!--Include the iframe-->
<br />
<br />
<iframe id="upload_frame" name="upload_frame" color= black frameborder="0" border="0" src="" scrolling="no" scrollbar="no" > </iframe>
<br />
<!---->
<br />
<input class="btn btn-blue" name="Submit" type="submit" id="submit" value="Submit" />
<br />
<br />
<?php if (isset($_GET['success'])) { ?>
<span style="color:#FFFFFF;" id="message" class="notice">Your file has been uploaded.</span>
<?php } ?>
</form>
</div>
<script>
function myFunction() {
document.getElementById("message").innerHTML = "";
}
/*document.getElementById('file').onchange = function () {
//alert('Selected file: ' + this.value);
var path = this.value;
var fileName = path.replace(/.*(\/|\\)/, '');
alert('Selected file: ' + fileName);
//myFunction(fileName);
};*/
</script>
</body>
</html>
try a simple example for understanding:
<?php
//php content
if ($_POST) { //here we are checking $_POST values that $_POST has some values.
//specify folder for file upload
$tempDir = __DIR__ . DIRECTORY_SEPARATOR . 'upload'; //it means make a directory uploads where this php file is kept.
if (!file_exists($tempDir)) { // if $tempDir is not there, so it will create that directory.
mkdir($tempDir);
}
if(!empty($_FILES))//now checking your uploaded file is not empty
{
$nm=$_FILES['file']['name']; //here $nm get the name of the file
$tmp=$_FILES['file']['tmp_name'];//$tmp get the temporary file stored path
$mDir = __DIR__ . DIRECTORY_SEPARATOR . 'uploads'. DIRECTORY_SEPARATOR .time().$nm; //this your destination path with time+nameof file as a name of file.
if(move_uploaded_file($tmp,$mDir)) //uploading file to your destination path, if uploaded then it will go in the if scope and echo.
{
echo "file uploaded with timestamp in uploads folder";
//now redirect from here any where
}
else
{
echo "fail to upload a file";
}
}
}
?>

Multiple Image insert taking extra one row after each insert

Here I am using this php code for insert multiple images in one field in database table but after insert a row is taking one extra row after each insert .......Help me to solve this issue..
Thank you Advance.
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
/*if(isset($_REQUEST['submit']))
{
$pname=$_FILES['image']['name'];
$tmp_name=$_FILES['image']['tmp_name'];
move_uploaded_file($tmp_name."photo/".$pname);
$fileext = pathinfo($pname, "photo/");
$fileext = strtolower($fileext);
}*/
$uploads_dir = 'photo/';
//$images_name ="";
foreach ($_FILES["image"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["image"]["tmp_name"][$key];
$name = $_FILES["image"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$images_name =$images_name.$name.",";
}
}
$sql=mysql_query("INSERT INTO multiimg(image) values('".$images_name."')");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function addmore(num)
{
if(num==1)
{
document.getElementById('field2').style.display='block';
document.getElementById('ni1').style.display='block';
return false;
}
else if(num==2)
{
document.getElementById('field3').style.display='block';
return false;
}
}
</script>
</head>
<body>
<form enctype="multipart/form-data" name="" action="" method="post">
<div id="field1">Enter One Image :<input type="file" name="image[]" id="img1"/>addmore...</div>
<div id="field2" style="display:none;">Enter Two Image :<input type="file" name="image[]" id="img2"/>add more...</div>
<div id="field3" style="display:none;">Enter Three Image :<input type="file" name="image[]" id="img3"/>addmore...</div>
<div id="field4" style="display:none">Enter Forth Image :<input type="file" name="image[]" id="img4"/>addmore...</div>
<input type="submit" name="submit"/>
</form>
</body>
</html>
please check if the form is posted then do the insert ,else while loading the page a row will be inserted in table with empty data
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
if(isset($_POST['submit'])){
$uploads_dir = 'photo/';
//$images_name ="";
foreach ($_FILES["image"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["image"]["tmp_name"][$key];
$name = $_FILES["image"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$images_name =$images_name.$name.",";
}
}
$sql=mysql_query("INSERT INTO multiimg(image) values('".$images_name."')");
}
?>

Displaying images retrieved from mongodb in web browser?

I am trying to retrieve an image from mongoDB and display it in web browser. But it is not working. Here is the code which I am using for insertion and retrieval
Code to upload:
<?php
//If you wanted to store the uploaded image in MongoDB, you could do the following in the script handling the form submission:
if(isset($_REQUEST['formsubmit']))
{
$m = new MongoClient();
$coll = $m->test;
$gridFS = $coll->getGridFS();
$tag = $_REQUEST['username'];
$gridFS->storeUpload('pic',array("tag"=>$tag));
echo 'File Uploaded Successfully';
$m->close();
}
?>
<!-- image and any file uploaded in mongodb -->
<html>
<head> Upload Image</head>
<body>
<!--The name of the uploaded file to store. This should correspond to the file field's name attribute in the HTML form. -->
<form method="POST" enctype="multipart/form-data">
<label for="username">Username:</label>
<input type="text" name="username" id="username" />
<label for="pic">Please upload a profile picture:</label>
<input type="file" name="pic" id="pic" />
<input type="submit" value="Register" name="formsubmit"/>
</form>
</body>
</html>
Code to retrieve image and display in browser:
<?php
//If you wanted to store the uploaded image in MongoDB, you could do the following in the script handling the form submission:
$m = new MongoClient();
$coll = $m->test;
$gridFS = $coll->getGridFS();
?>
<html>
<head>Displaying Image</head>
<body>
<?php
header('content-type: image/jpg');
echo '<img src=' . $gridFS->findOne(array("tag"=>"temp123"))->getBytes() .'>'. '</img>';
?>
</body>
</html>
Could anyone please help me out ??
Thank you
Really thankful for this wonderful opportunity to help you.
First of all..GridFS is using for saving files that more than 16mb size.You ain't mention on that question.
The below codes are for saving images less than 16mb.
***************** Image insertion**************
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["pic"]["name"]); //Image:<input type="file" id="pic" name="pic">
$tag = $_REQUEST['username'];
$m = new MongoClient();
$db = $m->test; //mongo db name
$collection = $db->storeUpload; //collection name
//-----------converting into mongobinary data----------------
$document = array( "user_name" => $tag,"image"=>new MongoBinData(file_get_contents($target_file)));
//-----------------------------------------------------------
if($collection->save($document)) // saving into collection
{
echo "One record successfully inserted";
}
else
{
echo "Insertion failed";
}
******************Image Retrieving******************
public function show()
{
$m=new MongoClient();
$db=$m->test;
$collection=$db->storeUpload;
$record = $collection->find();
foreach ($record as $data)
{
$imagebody = $data["image"]->bin;
$base64 = base64_encode($imagebody);
?>
<img src="data:png;base64,<?php echo $base64 ?>"/>
<?php
}
}
}
?>
Hope you will try this.Enjoy coding.Stay Blessed.

on upload get all file names in array in php

What i want to know is how can I get a list [specifically array] of all the files name in a directory when I select it through upload button, after which I would upload that array of files to the database. As one file as a single entry. So how do I do that?
No to forget that I just need files names and I have to upload these names only not the actual files.
are the files on the server? if you hopping to have a button you click on browser and open a folder on the end user this will not work. most browsers only allow single file selection
If you are using ftp, this function will return all of the filenames of a directory in an array.
function ftp_searchdir($conn_id, $dir) {
if(!#ftp_is_dir($conn_id, $dir)) {
die('No such directory on the ftp-server');
}
if(strrchr($dir, '/') != '/') {
$dir = $dir.'/';
}
$dirlist[0] = $dir;
$list = ftp_nlist($conn_id, $dir);
foreach($list as $path) {
$path = './'.$path;
if($path != $dir.'.' && $path != $dir.'..') {
if(ftp_is_dir($conn_id, $path)) {
$temp = ftp_searchdir($conn_id, ($path), 1);
$dirlist = array_merge($dirlist, $temp);
}
else {
$dirlist[] = $path;
}
}
}
ftp_chdir($conn_id, '/../');
return $dirlist;
}
<?
if (isset($_POST[submit])) {
$uploadArray= array();
$uploadArray[] = $_POST['uploadedfile'];
$uploadArray[] = $_POST['uploadedfile2'];
$uploadArray[] = $_POST['uploadedfile3'];
foreach($uploadArray as $file) {
$target_path = "upload/";
$target_path = $target_path . basename( $_FILES['$file']['name']);
if(move_uploaded_file($_FILES['$file']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['$file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<form enctype="multipart/form-data" action="upload-simple.php" method="POST">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload:
<input name="uploadedfile" type="file" />
</p>
<p>Choose a file to upload:
<input name="uploadedfile2" type="file" />
</p>
<p>Choose a file to upload:
<input name="uploadedfile3" type="file" />
<input name="submit" type="submit" id="submit" value="submit" />
</p>
</form>
</body>
</html>
This Might be Solve your Problems
If the files already exist on the server you can use glob
$files = glob('*.ext'); // or *.* for all files
foreach($files AS $file){
// $file is the name of the file
}

Categories