<form method="POST" action="crud.php" enctype="multipart/form-data" >
<div style="background-color:#252323; color:#FFFFFF; "><b>Image Gallery</b></div>
<table>
<tr>
<td valign="top">
<label for="description">Big Image</label>
</td>
<td valign="top" style="text-align:right">
<input type="file" name="image" /></br>
</td>
</tr>
<tr>
<td valign="top">
<label for="description">Thumbnail Image</label>
</td>
<td valign="top" style="text-align:right">
<input type="file" name="image" /></br>
</td>
</tr>
</table>
<input id="button" type="submit" value="Add" name="imagegalleryadd"/>
</form>
This is my form it has two upload images with one button i want to upload two images at the same time and put them in two separate column in the datase because i will use these two images in a slider one for big image and other for thumbnail i tried upload only one images and it was good but how do you upload two images at the same time this is my code for adding images. This code only uploads one images how can it be changed to upload two?
function AddImageGallery(){
global $dbh;
if(is_uploaded_file($_FILES["image"]['tmp_name'])){
$folder = "images/imagegallery/";
$file = basename( $_FILES['image']['name']);
$full_path = $folder.$file;
if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) {
echo "succesful upload, we have an image!";
$stmt = $dbh->prepare("INSERT INTO imagegallery (imggall_imageurl) VALUES (?)");
$stmt->bindValue(1,$full_path,PDO::PARAM_STR);
if($stmt->execute()){
echo "Image Recorded";
}else{
echo "Image was not Recorded";
}
} else {
echo "upload received! but process failed";
}
}else{
echo "upload failure ! Nothing was uploaded";
}
}
database will look like this
$sql ="CREATE TABLE IF NOT EXISTS $imagegallery (
imggall_id int(40) NOT NULL AUTO_INCREMENT PRIMARY KEY,
imggall_imageurl VARCHAR(1000) NOT NULL,
imggall_thumnailurl VARCHAR(1000) NOT NULL);" ;
$dbh->exec($sql);
UPDATE
new code i tried
function AddImageGallery(){
global $dbh;
if(is_uploaded_file($_FILES["bigimage"]['tmp_name'] && $_FILES["thumbnailimage"]['tmp_name'] )){
$folder = "images/imagegallery/";
$filebi = basename( $_FILES['bigimage']['name']);
$fileti = basename( $_FILES['thumbnailimage']['name']);
$fileti = basename( $_FILES['thumbnailimage']['name']);
$fullbi_path = $folder.$filebi;
$fullti_path = $folder.$fileti;
if(move_uploaded_file($_FILES['bigimage']['tmp_name'], $fullbi_path && $_FILES['thumbnailimage']['tmp_name'], $fullti_path )) {
echo "succesful upload, we have an image!";
$stmt = $dbh->prepare("INSERT INTO imagegallery (imggall_imageurl,imggall_thumnailurl) VALUES (?,?)");
$stmt->bindValue(1,$fullbi_path,PDO::PARAM_STR);
$stmt->bindValue(2,$fullti_path,PDO::PARAM_STR);
if($stmt->execute()){
header("Location: dashboard.php");
exit;
echo "Image Recorded";
}else{
echo "Image was not Recorded";
}
} else {
echo "upload received! but process failed";
}
}else{
echo "upload failure ! Nothing was uploaded";
}
}
<form method="POST" action="crud.php" enctype="multipart/form-data" >
<div style="background-color:#252323; color:#FFFFFF; "><b>Image Gallery</b></div>
<table>
<tr>
<td valign="top">
<label for="description">Big Image</label>
</td>
<td valign="top" style="text-align:right">
<input type="file" name="bigimage" /></br>
</td>
</tr>
<tr>
<td valign="top">
<label for="description">Thumbnail Image</label>
</td>
<td valign="top" style="text-align:right">
<input type="file" name="thumbnailimage" /></br>
</td>
</tr>
</table>
<input id="button" type="submit" value="Add" name="imagegalleryadd"/>
</form>
Quick Google:
http://php.net/manual/en/features.file-upload.multiple.php#53240
Shows a clear and simple method for multiple image uploads.
Quote:
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
if ($_FILES['upload']) {
$file_ary = reArrayFiles($_FILES['ufile']);
foreach ($file_ary as $file) {
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
}
}
For you:
<form method="POST" action="crud.php" enctype="multipart/form-data" >
<input type="file" name="image[]" />
<input type="file" name="image[]" />
<input id="button" type="submit" value="Add" name="imagegalleryadd"/>
</form>
Then using the earlier function linked
if ($_FILES['upload']) {
$file_ary = reArrayFiles($_FILES['ufile']);
$main = $file_ary[0]['name'];
$thumb = $file_ary[1]['name'];
// Upload to DB
}
<form method="POST" action="crud.php" enctype="multipart/form-data" >
<div style="background-color:#252323; color:#FFFFFF; "><b>Image Gallery</b></div>
<table>
<tr>
<td valign="top">
<label for="description">Big Image </label>
</td>
<td valign="top">
<input type="file" name="bigimage" /></br>
</td>
</tr>
<tr>
<td valign="top">
<label for="description">Thumbnail Image </label>
</td>
<td valign="top">
<input type="file" name="thumbnailimage" /></br>
</td>
</tr>
</table>
<input id="button" type="submit" value="Add" name="imagegalleryadd"/>
</form>
function AddImageGallery(){
global $dbh;
if(is_uploaded_file($_FILES["bigimage"]['tmp_name'] )){
$folder = "images/imagegallery/";
$filebi = basename( $_FILES['bigimage']['name']);
$fileti = basename( $_FILES['thumbnailimage']['name']);
$fileti = basename( $_FILES['thumbnailimage']['name']);
$fullbi_path = $folder.$filebi;
$fullti_path = $folder.$fileti;
if(move_uploaded_file($_FILES['bigimage']['tmp_name'], $fullbi_path)) {
if(move_uploaded_file($_FILES['thumbnailimage']['tmp_name'], $fullti_path )) {
echo "succesful upload, we have an image!";
$stmt = $dbh->prepare("INSERT INTO imagegallery (imggall_imageurl,imggall_thumnailurl) VALUES (?,?)");
$stmt->bindValue(1,$fullbi_path,PDO::PARAM_STR);
$stmt->bindValue(2,$fullti_path,PDO::PARAM_STR);
if($stmt->execute()){
header("Location: dashboard.php");
exit;
echo "Image Recorded";
}else{
echo "Image was not Recorded";
}
}
} else {
echo "upload received! but process failed";
}
}else{
echo "upload failure ! Nothing was uploaded";
}
}
anyone can try this out i was able to get what
If one is having difficulties with sending more than 1 image to .php it is crucial to put [] in the end of your name of input.
Thought I should mention that sine I spend last few hours wondering why PHP is not detecting more than 1 file.
Related
I'm very new to any web development issues and I couldn't find a solution to this problem. I have a form for uploading files so I use the enctype="multipart/form-data". However, I was also trying to take the fields from the form and encode them in a JSON file and read those out in a table in my html on my webpage. With the default enctype, the JSON encoding works great but obviously the file upload functionality doesn't work and vice versa. I followed a lot of W3Schools tutorials but I'm still lost. Is it possible to use two enctypes or what is the work around to this problem? I'm only uploading my files to localhost, no databases used. I apologize if I give too much info here but my form html looks like:
<form class="modal-content animate" enctype="multipart/form-data" method="post">
<div class="imgcontainer">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
</div>
<div class="container">
<label for="artist"><b>Artist Name</b></label>
<input class="form-control" type="text" placeholder="Enter name of artist" name="artist" required>
<label for="song"><b>Song Name</b></label>
<input class="form-control" type="text" placeholder="Enter name of song." name="song" required>
<label for="instrument"><b>Instrument Type</b></label>
<input class="form-control" type="text" placeholder="Enter type of instrument for tab." name="instrument" required>
<label for="myfile"><b>Tablature</b></label>
<input class="form-control" type="file" placeholder="Select your file." name="myfile" id="myfile" required>
<input type="submit" name="submit" value="Upload Tab PDF" class="w3-hover-purple" style="color:black; background-color:#A9A9A9"></input>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
</div>
</form>
My php code is structured as such:
<?php
$message = '';
$error = '';
if(isset($_POST["submit"])) {
if(empty($_POST["artist"])) {
$error = "<label class='text-danger'>Enter artist</label>";
}
else if(empty($_POST["song"])) {
$error = "<label class='text-danger'>Enter song name</label>";
}
else if(empty($_POST["instrument"])) {
$error = "<label class='text-danger'>Enter instrument</label>";
}
else if(empty($_POST["myfile"])) {
$error = "<label class='text-danger'>Enter file to upload</label>";
}
else {
if(file_exists('tablature.json')) {
$current_data = file_get_contents('tablature.json');
$array_data = json_decode($current_data, true);
$extra = array(
'artist' => $_POST['artist'],
'song' => $_POST['song'],
'instrument' => $_POST['instrument'],
'myfile' => $_POST['myfile']
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('tablature.json', $final_data)) {
$message = "<label class='text-success'>File Appended Successfully.</label>";
}
else {
$error = 'JSON File does not exist';
}
}
}
$target_dir = "Tablature/";
$target_file = $target_dir . basename($_FILES["myfile"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($target_file)) {
$error = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$error = "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $target_file)) {
$message = "The file has been uploaded.";
} else {
$error = "Sorry, there was an error uploading your file.";
}
}
}
?>
Finally, on my page I print out my JSON contents on my page like so:
<table style="width:100%">
<tr>
<th>Artist</th>
<td>Song Name</td>
<td>Instrument Type</td>
<td style="float:right; margin-right:100px;">File</td>
</tr>
<?php
$read_data = file_get_contents("tablature.json");
$read_data = json_decode($read_data, true);
print("Working<br>");
foreach($read_data as $row) {
print('<tr><th>'.$row["artist"].'</th><td>'.$row["song"].'</td><td>'.$row["instrument"].'</td><td style="float:right">'.$row["myfile"].'</td></tr>');
}
?>
</table><br>
Any help would be greatly appreciated. Thank you in advance.
When I run the following code I get this error:
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:\xampp\htdocs\pizda\aids\admin\addnew.php:73 Stack trace: #0
on line 73
<?php
error_reporting( ~E_NOTICE ); // avoid notice
require_once 'dbconfig.php';
if(isset($_POST['btnsave']))
{
$NaslovSrpski = $_POST['NaslovSrpski'];
$NaslovEngleski = $_POST['NaslovEngleski'];
$TekstSrpski = $_POST['TekstSrpski'];
$TekstEngleski = $_POST['TekstEngleski'];
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if(empty($NaslovSrpski)){
$errMSG = "Please Enter Username.";
}
else if(empty($NaslovEngleski)){
$errMSG = "Please Enter Your Job Work.";
}
else if(empty($TekstSrpski)){
$errMSG = "Please Enter Your Job Work.";
}
else if(empty($TekstEngleski)){
$errMSG = "Please Enter Your Job Work.";
}
else if(empty($imgFile)){
$errMSG = "Please Select Image File.";
}
else
{
$upload_dir = '../uploads/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
// rename uploading image
$userpic = rand(1000,1000000).".".$imgExt;
// allow valid image file formats
if(in_array($imgExt, $valid_extensions)){
// Check file size '5MB'
if($imgSize < 5000000) {
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else{
$errMSG = "Sorry, your file is too large.";
}
}
else{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
// if no error occured, continue ....
if(!isset($errMSG))
{
$stmt = $DB_con->prepare('INSERT INTO Obavestenja(NaslovSrpski,NaslovEngleski,TekstSrpski,TekstEngleski, Slika) VALUES(:naslovs, :naslove, :teksts, tekste, :upic)');
$stmt->bindParam(':naslovs',$NaslovSrpski);
$stmt->bindParam(':naslove',$NaslovEngleski);
$stmt->bindParam(':teksts',$TekstSrpski);
$stmt->bindParam(':tekste',$TekstEngleski);
$stmt->bindParam(':upic',$userpic);
if($stmt->execute())
{
$successMSG = "new record succesfully inserted ...";
header("refresh:5;index.php"); // redirects image view page after 5 seconds.
}
else
{
$errMSG = "error while inserting....";
}
}
}
include 'header.php';
?>
<div class="container">
<div class="page-header">
<h1 class="h2">add news. <a class="btn btn-default" href="index.php"> <span class="glyphicon glyphicon-eye-open"></span> view all </a></h1>
</div>
<?php
if(isset($errMSG)){
?>
<div class="alert alert-danger">
<span class="glyphicon glyphicon-info-sign"></span> <strong><?php echo $errMSG; ?></strong>
</div>
<?php
}
else if(isset($successMSG)){
?>
<div class="alert alert-success">
<strong><span class="glyphicon glyphicon-info-sign"></span> <?php echo $successMSG; ?></strong>
</div>
<?php
}
?>
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<table class="table table-bordered table-responsive">
<tr>
<td><label class="control-label">NaslovSrpski</label></td>
<td><input class="form-control" type="text" name="NaslovSrpski" placeholder="NaslovSrpski" value="<?php echo $NaslovSrpski; ?>" /></td>
</tr>
<tr>
<td><label class="control-label">NaslovEngleski</label></td>
<td><input class="form-control" type="text" name="NaslovEngleski" placeholder="NaslovEngleski" value="<?php echo $NaslovEngleski; ?>" /></td>
</tr>
<tr>
<td><label class="control-label">TekstSrpski</label></td>
<td><textarea class="form-control" type="text" name="TekstSrpski" placeholder="TekstSrpski" value="<?php echo $TekstSrpski; ?>" /></textarea></td>
</tr>
<tr>
<td><label class="control-label">TekstEngleski</label></td>
<td><textarea class="form-control" type="text" name="TekstEngleski" placeholder="TekstEngleski" value="<?php echo $TekstEngleski; ?>" /></textarea></td>
</tr>
<tr>
<td><label class="control-label">Profile Img.</label></td>
<td><input class="input-group" type="file" name="user_image" accept="image/*" /></td>
</tr>
<tr>
<td colspan="2"><button type="submit" name="btnsave" class="btn btn-default">
<span class="glyphicon glyphicon-save"></span> save
</button>
</td>
</tr>
</table>
</form>
You're missing a ":" in tekste's placeholder:
$stmt = $DB_con->prepare
('INSERT INTO Obavestenja' .
' (NaslovSrpski,NaslovEngleski,TekstSrpski,TekstEngleski, Slika)' .
' VALUES (:naslovs, :naslove, :teksts, :tekste, :upic)');
# ":" was missing here ----------------^
I have a problem with 1 part of upload section, how to make the code continue the process if the upload section is empty? I already make the code, but everytime i skip the file button, it show echo 'ERROR: Ekstensi file tidak di izinkan!'
Here is my code:
insert_form
<form name="pegawai" action="insert-proses.php" method="post" enctype="multipart/form-data">
<table width="700px" align="left" cellpadding="2" cellspacing="0">
<tr>
<td><b>NOKOM</b></td>
<td><b>:</b></td>
<td><input type="text" name="nokom" size="40" required /></td>
</tr>
<tr>
<td><b>NIP</b></td>
<td><b>:</b></td>
<td><input type="text" name="nip" size="40" required /></td>
</tr>
<tr>
<td><b>Nama</b></td>
<td><b>:</b></td>
<td><input type="text" name="nama" size="40" required /></td>
</tr>
<tr>
<td><b>Foto</b></td>
<td><b>:</b></td>
<td><input name="file" type="file" id="file" /></td>
</tr>
<tr>
<td></td>
<td></td>
<td><hr/><input type="submit" name="upload" value="Upload" /></td>
</tr>
</table>
</form>
insert-proses
<?php session_start();
include "config.php";
if(ISSET($_SESSION['superadmin'])) {
if($_POST['upload']) {
$nokom = $_POST['nokom'];
$nip = $_POST['nip'];
$nama = $_POST['nama'];
// Proses upload file
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$file_name = $_FILES['file']['name']; // Nama File
$file_ext = strtolower(end(explode('.', $file_name))); // Merubah nama file
$file_size = $_FILES['file']['size']; // Size File
$file_tmp = $_FILES['file']['tmp_name']; // Temp File
// Proses pengecekan upload file
if(in_array($file_ext, $allowed_ext) === true) {
if($file_size < 5220350) // Max upload file 5 MB / 1MB = 1044070 {
$lokasi = 'files/'.$nama.'.'.$file_ext;
move_uploaded_file($file_tmp, $lokasi);
$sql = "INSERT INTO pegawai (nokom,nip,nama,fileext,filegambar)
VALUES('$nokom','$nip','$nama','$file_ext','$lokasi')";
if (mysqli_query($conn, $sql)) {
echo "<script>alert('Insert data berhasil! Klik ok untuk melanjutkan');location.replace('pegawai-list.php')</script>";
}
else {
echo "Error updating record: " . mysqli_error($conn);
}
} else
{
echo '<div class="error">ERROR: Besar ukuran file (file size) maksimal 1 Mb!</div>';
}
} else
{
echo '<div class="error">ERROR: Ekstensi file tidak di izinkan!</div>';
}
}
} else
{
echo '<script>alert("Anda bukan Superadmin! Silahkan login menjadi Superadminterlebih dahulu");location.replace("index.php")</script>';
}
?>
Any help will be so thankful. Thanks
Jump over the complete upload part if there is no file uploaded, or better, run the upload part in your script only IF a file is uploaded:
if(isset($_FILES['file']) && is_array($_FILES['file'])) {
// your code to upload and check the file
}
Hi I can't seem to pinpoint what's wrong. I have a form with elements. Could you check the script? I just know it lacks something but a noob like me just doesn't know. Basically when the Smart Money radio button is selected, the BPI is disabled,and vice versa. It should insert the data inputs in the db. It works fine if the selected radio btn is BPI but if Smart money was selected and the user inputs data and BPI/file upload disabled, it doesn't insert anything in the db. Can you please show me what to do I think the scripts are kinda placed wrong, because the query is below the file upload script. I think it doesn't insert anything when there is nothing to upload/that option is disabled. The file upload script interferes I guess.
PHP:
if(isset($_FILES['filename'])){
$errors = array();
$file_name = $_FILES['filename']['name'];
$file_size =$_FILES['filename']['size'];
$file_tmp =$_FILES['filename']['tmp_name'];
$file_type=$_FILES['filename']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['filename']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
// if no error...
if (empty($errors)==true) {
// upload the file...
move_uploaded_file($file_tmp,"uploads/".$file_name);
$servername = "localhost";
$username = "root";
$password = " ";
$dbname = "admin";
// create new record in the database
include ("dbinfo.php");
mysql_query("INSERT INTO payment_form (Tracking, date, mode, ContactNo, totalsent, datesent, filename) VALUES ('$transactionNo', NOW(), '$rad', '$contactNo', '$totalSent', '$dateSent', '$file_name')") ;
header('Location: paymentform_success.php');
}else{
print_r($errors);
}
}
Form:
<form name="form" method="POST" enctype="multipart/form-data">
<table width="416" height="245" border="1" align="center">
<tr>
<td colspan="2">Transaction No: <input type="text" name="transaction_no" id="transaction_no" /> </td>
</tr>
<tr>
<td colspan="2" align="center">Please select the mode of payment</td>
</tr>
<tr>
<td width="183" align="center"><input name="rad" type="radio" onclick="enableField(this)" value="Smart Money">
Smart Money</td>
<td width="201" align="center"><input name="rad" type="radio" onclick="enableField(this)" value="BPI"> BPI Bank Deposit</td>
</tr>
<tr>
<td align="center"><input name="contactno" type="text" disabled="disabled" id="contactno"></td>
<td align="center"><input name="filename" type="file" id="filename" disabled="disabled"/></td>
</tr>
<tr>
<td>Total amount sent:</td>
<td> <input type="text" name="totalsent" id="totalsent" /></td>
</tr>
<tr>
<td>Date sent:</td>
<td> <input type="text" name="datesent" id="datesent" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input name="submit" type="submit" id="submit" value="Submit" /></td>
</tr>
</table>
<input type="hidden" name="MM_insert" value="form" />
</form>
JS for disable/enable
<script type="text/javascript">
function enableField(obj){
var form=obj.form;
var txtNames=['contactno','filename'], f;
var rads=document.getElementsByName(obj.name), r, i=0;
while(r=rads[i++]){
f=form[txtNames[i-1]];
if(r.checked){
f.removeAttribute('disabled');
f.focus();
}
else{
f.value='';
f.setAttribute('disabled','disabled')
}
}
}
</script>
Do the INSERT outside the if(isset($_FILES['filename'])) block.
if (isset($_POST['submit'])) {
$errors = array();
if (isset($_FILES['filename'])) {
$file_name = $_FILES['filename']['name'];
$file_size =$_FILES['filename']['size'];
$file_tmp =$_FILES['filename']['tmp_name'];
$file_type=$_FILES['filename']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['filename']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
// if no error...
if (empty($errors)==true) {
// upload the file...
move_uploaded_file($file_tmp,"uploads/".$file_name);
}else{
print_r($errors);
}
} else {
$file_name = '';
}
if (empty($errors)) {
$servername = "localhost";
$username = "root";
$password = " ";
$dbname = "admin";
// create new record in the database
include ("dbinfo.php");
$transactionNo = $_POST['transaction_no'];
$rad = $_POST['rad'];
$contactNo = $_POST['contactno'];
$totalSent = $_POST['totalsent'];
$dateSent = $_POST['datesent'];
mysql_query("INSERT INTO payment_form (Tracking, date, mode, ContactNo, totalsent, datesent, filename) VALUES ('$transactionNo', NOW(), '$rad', '$contactNo', '$totalSent', '$dateSent', '$file_name')") ;
header('Location: paymentform_success.php');
}
}
Unable to upload image into database. After submitting the form, I am getting this error:
There was an error uploading the data, please try again!
My code is given below please help me regarding this.
<?php
extract($_POST);
extract($_GET);
error_reporting(0);
?>
<html>
<head>
<!-- Date Picker Starts -->
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="js/script.js"></script>
<script>
$(document).ready(function() {
$(function() {
$(".datepicker").datepicker({ dateFormat: 'dd-mm-yy' });
});
});
</script>
<!-- Date Picker Ends -->
<script>
function getccname(val)
{
if(val == 'company')
{
document.getElementById("colname").disabled= true;
document.getElementById("course").disabled = true;
document.getElementById("year").disabled = true;
}
else if(val == 'college')
{
document.getElementById("comname").disabled = true;
document.getElementsByName("doj")[0].disabled= true;
document.getElementById("colname").disabled = false;
document.getElementById("course").disabled = false;
document.getElementById("year").disabled = false;
}
else
{
document.getElementById("comname").disabled = false;
document.getElementsByName("doj")[0].disabled= false;
document.getElementById("colname").disabled = false;
document.getElementById("course").disabled = false;
document.getElementById("year").disabled = false;
}
}
</script>
<!-- nice editor -->
<script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script>
<script type="text/javascript">bkLib.onDomLoaded(nicEditors.allTextAreas);</script>
<!-- nice editor end -->
</head>
<body>
<?php
include("menu.php");
?><br>
<?php
include("database.php");
if(isset($_POST['submit']))
{
$uploadpath= 'upload/'; // directory to store the uploaded files
$max_size = 2000; // maximum file size, in KiloBytes
$alwidth = 900; // maximum allowed width, in pixels
$alheight = 800; // maximum allowed height, in pixels
$allowtype = array('bmp', 'gif', 'jpg', 'jpe', 'jpeg', 'png'); // allowed extensions
if(isset($_FILES['fileup']) && strlen($_FILES['fileup']['name']) > 1)
{
$timestamp = time();
$uploadpath = $uploadpath . $timestamp . basename( $_FILES['fileup']['name']); // gets the file name
$sepext = explode('.', strtolower($_FILES['fileup']['name']));
$type = end($sepext); // gets extension
list($width, $height)= getimagesize($_FILES['fileup']['tmp_name']); // gets image width and height
$err = ''; // to store the errors
// Checks if the file has allowed type, size, width and height (for images)
if(!in_array($type, $allowtype)) $err .= 'The file: <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
if($_FILES['fileup']['size'] > $max_size*1000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB.';
if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x '. $alheight;
// If no errors, upload the image, else, output the errors
if(is_uploaded_file($_FILES['fileup']['name']))
{
move_uploaded_file( $_FILES['fileup']['tmp_name'], $uploadpath) ;
$file =$uploadpath;
$name =$_POST["name"];
$fname =$_POST["fname"];
$gender =$_POST["gender"];
$email =$_POST["email"];
$date =$_POST["date"];
$mn =$_POST["mn"];
$pn =$_POST["pn"];
$address=$_POST["address"];
$idnum =$_POST["idnum"];
$ccname =$_POST["ccname"];
$colname=$_POST["colname"];
$course =$_POST["course"];
$year =$_POST["year"];
$comname=$_POST["comname"];
$doj =$_POST["doj"];
$result=mysql_query("insert into registration(file,name,fname,gender,email,date,mn,pn,address,idnum,ccname,colname,course,year,comname,doj)
values('$uploadpath','$name','$fname','$gender','$email','$date','$mn','$pn','$address','$idnum','$ccname','$colname','$course','$year','$comname','$doj')");
print_r($result);
echo "Inserted Successfully";
}
}
else
{
echo "There was an error uploading the data, please try again!";
}
}
?>
<form name="form" method="post" action="" onSubmit="submit;">
<center><table border="1" cellspacing="0" style="width:500px">
<tr>
<td><b>Image</td> <td><input type="file" name="fileup" id="fileup" size="25" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td></tr>
<tr>
<td>Father Name</td>
<td><input type="text" name="fname"></td></tr>
<tr><td>Gender</td>
<td><select name="gender">
<option value ="na">Select</option>
<option value ="Male">Male</option>
<option value ="Female">Female</option>
</td></tr>
<tr>
<td>Email</td>
<td><input type="text" name="email"></td></tr>
<tr>
<td>Date Of Birth</td>
<td><input type="text" name="date" class="datepicker" required></td></tr>
<tr>
<td>Mobile Number</td>
<td><input type="text" name="mn"></td></tr>
<tr>
<td>Parent Number</td>
<td><input type="text" name="pn"></td></tr>
<tr>
<td>Address</td> <td><textarea name="address" rows="3" cols="50"></textarea></td>
</tr>
<tr>
<td>Coll/Comp ID Num</td>
<td><input type="text" name="idnum"></td></tr>
<tr><td>Company/College</td>
<td><select name="ccname" onchange="getccname(this.value);">
<option value ="na">Select</option>
<option value ="company">Company</option>
<option value ="college">College</option>
</td></tr>
<tr>
<td>College Name</td>
<td><input type="text" name="colname" id="colname"></td></tr>
<tr>
<td>Course</td>
<td><input type="text" name="course" id="course"></td></tr>
<tr>
<td>Year</td>
<td><input type="text" name="year" id="year"></td></tr>
<tr>
<td>Company Name</td>
<td><input type="text" name="comname" id="comname"></td></tr>
<tr>
<td>Date Of Join</td>
<td><input type="text" name="doj" class="datepicker"></td></tr>
<tr>
<td colspan="2" align="center"><input class="button" type="submit" name="submit" value="submit"/>
<input class="button" type="reset" name="Reset" value="Reset " /> </td>
</tr></center>
</table>
</form>
</body>
</html>
try this,Then include your insert query it will work enctype="multipart/form-data"
<form name="form" method="post" action="" onSubmit="submit;" enctype="multipart/form-data">
</form>
<?php
if(isset($_FILES['image']))
{
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$value = explode(".", $file_name);
$file_ext = strtolower(array_pop($value));
//$file_ext=strtolower(end(explode(".",$file_name))); -->this line wnt work bcoz only variable should be passed inside explode
$expensions= array("jpeg","jpg","png","csv");
if(in_array($file_ext,$expensions)== false)
{
$errors="Extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152)
{
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true)
{
move_uploaded_file($file_tmp,"upload/".$file_name);
**//include here insert query**
echo "Success";
}else
{
print_r($errors);
}
}
?>
1st. do not use mysql_* functions, use mysqli_* instead.
2nd. This is a very big security hole, if accept any data.
3rd. Whay do you create variables like this? $name=$_POST["name"];
So, when you want to insert the $_POST["name"] do something like this:
EDIT:
Try this. It will die, and will print out the query string for you. Try to copy that directly into the mysql, and comment the result.
function dbEscape($str) {
return mysql_real_escape_string($str);
}
$sql = "INSERT INTO registration(file,name,fname,gender,email,date,mn,pn,address,idnum,ccname,colname,course,year,comname,doj)
VALUES ('".dbEscape($uploadpath)."','". dbEscape($_POST["name"])."','". dbEscape($_POST['fname'])."','". dbEscape($_POST['genred'])."','". dbEscape($_POST['email'])."','". dbEscape($_POST['date'])."','". dbEscape($_POST['mn'])."','". dbEscape($_POST['pn'])."','". dbEscape($_POST['address'])."','". dbEscape($_POST['idnum'])."','". dbEscape($_POST['ccname'])."','". dbEscape($_POST['colname'])."','". dbEscape($_POST['course'])."','". dbEscape($_POST['year'])."','". dbEscape($_POST['comname'])."','". dbEscape($_POST['doj'])."')";
die($sql);
$result = mysql_query($sql);
Your form does not contain enctype="multipart/form-data" and is an essential part of uploading files.
Modify your form to read as:
<form name="form" method="post" enctype="multipart/form-data" action="" onSubmit="submit;">
that is the reason why your upload does not work.