PHP code is not working when there no data? - php

I'm doing data entry program based on PHP every thing is working no issue (still under construction) but there is a problem that I can't find a solution. The issue is when the database doesn't have any data the image path wont get registered.
Now I'm using uplodify to upload an image file at the same moment I'm sending some data as well. The data contains a name, contact details and description this will directly be inserted to the DB and I also upload image which will get saved in to a folder and the name get saved in the database. But this processes are handled by two different PHP files one is AddPOIPro.PHP which handles the data adding and the uplodify.php to handle file upload and the updating of the file name.
The first issue I had was uplodify was not adding the file name in the same row as the submitted data so what I did was to get the last ID and decrement it by one and the updated the row that works when there is data but when theirs no data it fails. So what should I do to over come this. Below is my complete scripts thank you for your time.
Form
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('lId.php');
?>
<!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" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="Upl/jquery.uploadify.min.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(function() {
$('#imgUpload').uploadify({
'auto' : false,
'swf' : 'Upl/uploadify.swf',
'uploader' : 'Upl/uploadify.php',
'height' : 20,
'width' : 200,
}
// Put your options here
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#sendData").click(function(){
var name = document.getElementById("Name").value;
var desc = document.getElementById("Descrip").value;
var con = document.getElementById("ConInfo").value;
var dataString = 'Name='+name+'&Descrip='+desc+'&ConInfo='+con;
$.ajax({
type:'POST',
data:dataString,
url:'AddPoiPro.php',
success:function(data){
if(data="Data inserted") {
//alert("Data Success");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: #060\">Data Saved</dive>";
$('#msg').delay(1500).fadeOut();
} else {
//alert("Not Inserted");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: red\">Data Not Saved</div>";
}
}
});
});
});
</script>
<link rel="stylesheet" type="text/css" href="Upl/uploadify.css" />
<title>AddPOI</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<label for="poiid">ID :</label>
<input type="text" name="poiid" id="poiid" readonly="readonly" style="width:70px;" value="<?php echo $tId; ?>" />
</p>
<p>
<label for="Name">POI Name :</label>
<input type="text" name="Name" id="Name" />
</p>
<p>
<label for="Descrip" style="alignment-adjust:middle">POI Description :</label>
<textarea name="Descrip" id="Descrip" cols="45" rows="5"></textarea>
</p>
<p>
<label for="ConInfo">Contact Infomation :</label>
<textarea name="ConInfo" id="ConInfo" cols="45" rows="5"></textarea>
</p>
<p>
<label for="Img">POI Image</label>
<input type="file" name="imgUpload" id="imgUpload" />
</p>
<p><div id="msg"></div></p>
<p>
<div align="center">
<input type="button" name="Submit" id="sendData" value="Submit" onclick="$('#imgUpload').uploadify('upload','*');" style="width:100px;" />
<input type="reset" name="reset" id="reset" value="Rest Data" style="width:100px;" />
</div>
</p>
</form>
</body>
</html>
Process PHP
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('connect.php');
$getId = mysql_query("SELECT ID FROM poiinfo");
$row = mysql_fetch_array($getId);
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
if($row['ID']== 1){
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE 1";
$updDone = mysql_query($updLn);
if ($updDone){
echo "Data inserted";
}else {
echo "Not Done";
}
}else {
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
}
?>
uplodify php
<?php
/*
Uploadify
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
include ('../../POIWeb/connect.php');
include ('../../POIWeb/lId.php');
// Define a destination
$path = 'POIWeb/img/';
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $path ; // Relative to the root
/*$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo $fName;
echo '1';
} else {
echo 'Invalid file type.';
}
}*/
//if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetFile = $targetPath . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
$tId = $tId--;
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
$fName = $_FILES['Filedata']['name'];
$imgPath = "UPDATE poiinfo SET Img = '$fName' WHERE ID = '$tId'";
mysql_query($imgPath);
echo '1';
} else {
echo 'Invalid file type.';
}
?>
Please help.

To get Last id you can do Query As Like Following
SELECT `ID`
FROM `poiinfo`
ORDER BY `ID` DESC
LIMIT 0 , 1
If you face any more problem then you can knock me..

I think this would be a better approach
$("#sendData").click(function(){
//upload the file programatically (Method Call'upload')[http://www.uploadify.com/documentation/uploadify/upload/]
// echo the name of the uploaded file (make sure to rename the file for uniquiness)
// create a hidden element with the filename as the value inside the form
// call the ajax submit and submit the form. You can use (onuploadsuccess)[http://www.uploadify.com/documentation/uploadify/onuploadsuccess/] to trigger the element creation and ajax submit functions
});
You current implementation can cause issues consider,
Request 1 : ID 10
Upload 1 : ID 10
Request 2 : ID 11
Request 3 : ID 12
Upload 2 : ID 12
Upload 3 : ID 12

I found the Solution to my problem had some help form the guys in StackOverflow Below is my full code is any one is having the same problem similar to me you can use this code. And if it works for you pls put a vote for me thank you.
My Data Entry Form
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('lId.php');
?>
<!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" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="Upl/jquery.uploadify.min.js"></script>
<script type="text/javascript">
$(function() {
$(function() {
$('#imgUpload').uploadify({
'auto' : false,
'swf' : 'Upl/uploadify.swf',
'uploader' : 'Upl/uploadify.php',
'height' : 20,
'width' : 200,
'fileTypeDesc' : 'Image Files',
'fileTypeExts' : '*.gif; *.jpg; *.png'
});
// Put your options here
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#save_data").click(function(){
var name = document.getElementById("Name").value;
var desc = document.getElementById("Descrip").value;
var con = document.getElementById("ConInfo").value;
var dataString = 'Name='+name+'&Descrip='+desc+'&ConInfo='+con;
$.ajax({
type:'POST',
data:dataString,
url:'AddPoiPro.php',
success:function(data){
if(data="Data inserted") {
//alert("Data Success");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: #060\">Data Saved</dive>";
$('#msg').delay(1500).fadeOut();
} else {
//alert("Not Inserted");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: red\">Data Not Saved</div>";
$('#msg').delay(1500).fadeOut();
}
}
});
});
});
</script>
<link rel="stylesheet" type="text/css" href="Upl/uploadify.css" />
<title>AddPOI</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<label for="poiid">ID :</label>
<input type="text" name="poiid" id="poiid" readonly="readonly" style="width:70px;" value="<?php echo $tId; ?>" />
</p>
<p>
<label for="Name">POI Name :</label>
<input type="text" name="Name" id="Name" />
</p>
<p>
<label for="Descrip" style="alignment-adjust:middle">POI Description :</label>
<textarea name="Descrip" id="Descrip" cols="45" rows="5"></textarea>
</p>
<p>
<label for="ConInfo">Contact Infomation :</label>
<textarea name="ConInfo" id="ConInfo" cols="45" rows="5"></textarea>
</p>
<p>
<label for="Img">POI Image</label>
<input type="file" name="imgUpload" id="imgUpload" />
</p>
<p><div id="msg"></div></p>
<p>
<div align="center">
<input type="button" name="Submit" id="save_data" value="Submit" onclick="$('#imgUpload').uploadify('upload','*');" style="width:100px;" />
<input type="reset" name="reset" id="reset" value="Rest Data" style="width:100px;" />
</div>
</p>
</form>
</body>
</html>
My DataProcess PHP
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('connect.php');
$getId = mysql_query("SELECT ID FROM dbname");
$row = mysql_fetch_array($getId);
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
if($row['ID']== 1){
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE 1";
$updDone = mysql_query($updLn);
if ($updDone){
echo "Data inserted";
}else {
echo "Not Done";
}
}else {
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
}
?>
This was really tricky the uploadify PHP but got it to work the way I want.
Uplodify PHP (My Version)
<?php
/*
Uploadify
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
include ('../../POIWeb/connect.php');
include ('../../POIWeb/lId.php');
// Define a destination
$path = 'POIWeb/img/';
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $path ; // Relative to the root
/*$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo $fName;
echo '1';
} else {
echo 'Invalid file type.';
}
}*/
//if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetFile = $targetPath . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
$tId = $tId--;
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
$fName = $_FILES['Filedata']['name'];
$imgPath = "UPDATE poiinfo SET Img = '$fName' WHERE ID = '$tId'";
mysql_query($imgPath);
echo '1';
} else {
echo 'Invalid file type.';
}
?>
This script is working flawlessly now if some face the same situation which I faced use this and see if it works for you and you're allowed to make any changes as well.
Thank you.

Related

how can I upload a pdf and an image in php mysql

I am trying to upload a pdf file and an image in php mysql but it seems that the move_uploaded_file function can only work with one file. I have tried to make it work with both files but it doesn't seem to me working. It moves just the images to the target folder and adds both image name and pdf name to the database but it doesn't move the pdf to target folder. This is the code. pls help
<?php
session_start();
require_once("includedfunctions.php");
include 'dbh.php';
if (isset($_POST['submit'])){
$title=$_POST['title'];
$author=$_POST['author'];
$target = "img/pic_book/";
$target2 = "img/pdf/";
$imgname = basename($_FILES["cphoto"]["name"]);
$bookname = basename($_FILES["book"]["name"]);
$newname = $target.basename($_FILES["cphoto"]["name"]);
$newname2 = $target2.basename($_FILES["book"]["name"]);
$img_type = pathinfo($newname,PATHINFO_EXTENSION);
$book_type = pathinfo($newname2,PATHINFO_EXTENSION);
if($img_type!='jpg' && $img_type!='JPG' && $img_type!='png' && $img_type!='PNG'){
$message="Please ensure you are entering an image";
}else{
if($book_type != 'pdf'){
$message="books must be uploaded in pdf format";
}else{
if(!preg_match("/^[a-zA-Z'-]+$/",$author)){
$message = "<p style='color:red'>Please enter the real name of the author; not a nickname.</p>";
}else{
if (move_uploaded_file($_FILES["cphoto"]["tmp_name"], $newname)) {
if(move_uploaded_file($_FILES["book"]["tmp_name"], $newname2));{
$sql = "INSERT INTO books (Title, Author, pathtopdf, pathtoimage) VALUES ('$title', '$author', '$bookname', '$imgname')";
$result = mysqli_query($conn, $sql);
if($result){
$message = "upload successful";
}else{
$message = "upload failed1";
}
}
}else{
$message = "upload failed";
}
}
}
}
}
else{
$message="";
$title="";
}
?>
<html>
<head>
<title>Libraria</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/contactcss.css" rel="stylesheet">
<script src="js/respond.js"></script>
</head>
<body>
<br><br><br><br><br>
<!-- content -->
<div class="container">
<?php
echo '<p>Welcome ' . $_SESSION['name']. '</p><br>';
echo '<p>' . $message. ' </p>';
?>
<br><br>
<!--form-->
<div class="row">
<form action="admin2.php" method = "post" enctype="multipart/form-data">
<label for="Title">Title</label><br>
<input type="text" id="fname" value ="<?php echo $title; ?>" name="title" placeholder="Title of the book" required><br>
<label for="author">Author</label><br>
<input type="text" id="lname" name="author" placeholder="Author of the book" required><br>
<label for="Cover photo">Cover photo</label><br>
<input type="file" id="cphoto" name="cphoto" required><br>
<label for="book">Book</label>
<input type="file" id="book" name="book" required><br>
<button class="submit" type="submit" name="submit"><b>Upload</b></button>
</form>
</div>
</div>
</body>
</html>
Code is all correct. just check pdf size. if size is more than 4MB than it will not allowed to upload. you need to increase upload file size in php.ini file or apache config settting file.
Have a great day :)
application/pdf is the mime type for pdf not just pdf.

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";
}
}
}
?>

Show file link after uploading

I've downloaded an image uploading script with Ajax from this Link
The codes are:
index.php
<script language="javascript" type="text/javascript">
<!--
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
document.getElementById('f1_upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success, str){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('f1_upload_process').style.visibility = 'hidden';
document.getElementById('f1_upload_form').innerHTML = result + str+'<label>File: <input name="myfile" type="file" size="30" /><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
document.getElementById('f1_upload_form').style.visibility = 'visible';
return true;
}
//-->
</script>
</head>
<body>
<div id="container">
<div id="header"><div id="header_left"></div>
<div id="header_main">Max's AJAX File Uploader</div><div id="header_right"></div></div>
<div id="content">
<form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
<p id="f1_upload_process">Loading...<br/><img src="loader.gif" /><br/></p>
<p id="f1_upload_form" align="center"><br/>
<label>File:
<input name="myfile" type="file" size="30" />
</label>
<label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" />
</label>
</p>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
</div>
<div id="footer">Powered by AJAX F1</div>
</div>
</body>
Uploader.php
<?php
// Edit upload location here
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$result = 0;
$target_path = $destination_path . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
// echo $target_path;
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result.",".$target_path; ?>);</script>
I want to show the url of uploaded image. So that it can be use instantly.
I've a little knowledge about ajex. I tried by writing two three of codes but it's not working.
Anyone can help to show the file url.
Thanks in advance.
Hope this helps...
index.php
<html>
<head>
<script src="js/jquery-2.1.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
document.getElementById('f1_upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success, str, filename){
var result = '';
var file_link = '';
var location = window.location.href;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
file_link = "<br/><a href='"+directoryPath+"/"+filename +"'>"+filename+"</a><br/>";
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('f1_upload_process').style.visibility = 'hidden';
document.getElementById('f1_upload_form').innerHTML = result + file_link +'<br/><br/><label>File: <input name="myfile" type="file" size="30" /><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
document.getElementById('f1_upload_form').style.visibility = 'visible';
return true;
}
//-->
</script>
</head>
<body>
<div id="container">
<div id="header"><div id="header_left"></div>
<div id="header_main">Max's AJAX File Uploader</div><div id="header_right"></div></div>
<div id="content">
<form action="ajax-uploader.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
<p id="f1_upload_process">Loading...<br/><img src="loader.gif" /><br/></p>
<p id="f1_upload_form" align="center"><br/>
<label>File:
<input name="myfile" type="file" size="30" />
</label>
<label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" />
</label>
</p>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
</div>
<div id="footer">Powered by AJAX F1</div>
</div>
</body>
</body>
</html>
ajax-uploader.php
<?php
// Edit upload location here
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$result = 0;
$target_path = $destination_path . basename( $_FILES['myfile']['name']);
$actual_name = basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
// echo $target_path;
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.stopUpload(<?php echo "$result, '$target_path','$actual_name' "; ?>);</script>
change Uploader.php to upload.php.
Add php code after sleep as follows..
sleep(1);
$target_path = str_replace('\\', '/', $target_path);
$spath = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI'])."/".$_FILES['myfile']['name'];
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo "'".$result."','".$target_path.',img url :'.$spath."'";?>);</script>

Mysqli 2 records being created with one insert

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')");
}
?>

How to send a data from my form to uplodify.php

I'm trying to send my database row ID from this form to the uploadify.php so it can update that row with the file name but it's not happening when I run the same scrip with insert with out any ID the name get entered to the row below the needed data row. What should I do please help.
This is my form.php
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>UploadiFive Test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="Upl/jquery.uploadify.min.js"></script>
<link rel="stylesheet" type="text/css" href="Upl/uploadify.css" />
<style type="text/css">
body {
font: 13px Arial, Helvetica, Sans-serif;
}
</style>
<?php
include ('lId.php')
?>
<script type="text/javascript">
$(function() {
$('#imgUpload').uploadify({
'auto' : false,
'swf' : 'Upl/uploadify.swf',
'uploader' : 'Upl/uploadify.php',
'height' : 20,
'width' : 200,
'fileTypeDesc' : 'Image Files',
'fileTypeExts' : '*.gif; *.jpg; *.png',
'method' : 'POST',
'scriptData' : {'iD' : "<?php echo $tId; ?>" },
// Put your options here
});
});
</script>
</head>
<body>
<h1>Uploadify Demo</h1>
<p>
<label for="poiid">ID :</label>
<input type="text" name="poiid" id="poiid" readonly="readonly" style="width:70px;" value="<?php echo $tId; ?>" />
</p>
<form enctype="multipart/form-data" method="POST">
<div id="queue"></div>
<input id="imgUpload" name="imgUpload" type="file" multiple="true" />
Upload Files
</form>
</body>
</html>
my upldify.php
<?php
/*
Uploadify
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
include ('../../POIWeb/connect.php');
// Define a destination
$sId = $_REQUEST['iD'];
$path = 'POIWeb/img/';
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $path ; // Relative to the root
/*$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo $fName;
echo '1';
} else {
echo 'Invalid file type.';
}
}*/
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetFile = $targetPath . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
$fName = $_FILES['Filedata']['name'];
//$imgPath = "INSERT INTO poiinfo(`Img`) VALUES ('$fName')";
$imgPath = "UPDATE poiinfo SET Img = '$fName' WHERE ID = '$sId'";
mysql_query($imgPath);
echo '1';
} else {
echo 'Invalid file type.';
}
}
?>
Use 'formData' instead of 'scriptData'. And get the data in $_POST array.
This code Upload Files is not needed
But uploadify uploads files directly - it means you need add next names of files, don't rewrite.

Categories