php image upload mysql database - php

I have problem with my script. It uploads image in my hosting server. There created folders with images are missing from hosting server next day or next week not all images of course - 18-19% of all for 2 weeks. I asked them. They told me- the problem is in my php code. If someone can help I will be happy. May be I add some 0777 in mkdir()???? I don't know. I am thinking at the all time...
<?php
if (isset($_FILES['myfile'])) {
$ip = getRealIpAddr();
$usernameupload = $user_data['username'];
$title = sanitize($_POST['title']);
$description = sanitize($_POST['description']);
if (empty($_POST['folder']) === true) { $folder = sanitize($_POST['folder_option']);} else { $folder = sanitize($_POST['folder']);}
$date = date('M-d-Y');
$code = "";
$errors = array();
$allowed_ext =array('jpg', 'jpeg', 'png', 'gif');
$file_name = $_FILES['myfile']['name'];
$file_size = $_FILES['myfile']['size'];
$file_tmp = $_FILES['myfile']['tmp_name'];
$extension=explode('.',$file_name);
$file_ext=strtolower(end($extension));
if (isset($_POST['submitupload'])) {
if ($_FILES['myfile']['name'] == ""){
$errors[] = ' *Upload file';
} else if (in_array($file_ext, $allowed_ext) === false) {
$errors[] = ' *Extension not allowed';
}
}
if ($file_size > 5042880) {
$errors[] = 'File size must be under 5mb';
}
if (strlen($folder) > 50) {
$errors[] = 'Your new folder name must be max 50 characters';
}
if (empty($_POST['title'])) {
$errors[] = 'Please Fill Title';
}
if (strlen($_POST['title']) > 255) {
$errors[] = 'Your title must be max 255 characters';
}
if (empty($errors)) {
require('db.inc.php');
$charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
$length = 50;
for ($i = 0; $i <= $length; $i++) {
$rand = rand() % strlen($charset);
$tmp = substr($charset, $rand, 1);
$code .= $tmp;
}
$query = mysql_query("SELECT code FROM files WHERE code='$code'");
$numrows = mysql_num_rows($query);
while ($numrows != 0) {
for ($i = 0; $i <= $length; $i++) {
$rand = rand() % strlen($charset);
$tmp = substr($charset, $rand, 1);
$code .= $tmp;
}
$query = mysql_query("SELECT code FROM files WHERE code='$code'");
$numrows = mysql_num_rows($query);
}
mkdir("files/$code");
mkdir("files/thumbs/$code");
if (move_uploaded_file($file_tmp, "files/$code/".$file_name)) {
$file = "";
$query = mysql_query("INSERT INTO files VALUES ('', '$usernameupload', '$ip', '$title', '$code', '$folder', '$description', '$file_name', '$file_ext', '$file_size', '$date')");
$query1 = mysql_query("INSERT INTO votes VALUES ('', '', '', '$code')");
create_thumb('files/'.$code.'/', $file_name, 'files/thumbs/' . $code . '/');
header("Location: userdownload.php?code=$code");
exit();
}
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<table>
<tr>
<td id="editfill">Image:*</td>
<td><input type="file" name="myfile" id="fileup"></td>
<tr>
<td></td>
<td><?php
if (isset($_POST['submitupload'])) {
if ($_FILES['myfile']['name'] == ""){
echo '<div id="errormsg"> *Upload file </div>';
} else if (in_array($file_ext, $allowed_ext) === false) {
echo '<div id="errormsg"> *Allowed extension: .jpg, .jpeg, .png, .gif</div>';
} else if ($file_size > 5042880) {
echo '<div id="errormsg"> *File size must be under 5mb </div>';
}
}
?></td>
</tr>
</tr>
<tr>
<td id="editfill">Title:*</td>
<td><input type="text" name="title" id="title" value="<?php if (isset($_POST['submitupload'])) echo htmlentities($_POST['title']); ?>" maxlength="255"></td>
<tr>
<td></td>
<td><?php
if (isset($_POST['submitupload'])) {
if (empty($_POST['title'])) {
echo '<div id="errormsg"> *Please fill title </div>';
}
if (strlen($_POST['title']) > 255) {
echo '<div id="errormsg"> *Your title must be max 255 characters</div>';
}
}
?></td>
</tr>
</tr>
<tr>
<td id="editfill">Create Album:</td>
<td><input type="text" name="folder" id="title" value="<?php if (isset($_POST['submitupload'])) echo htmlentities($_POST['folder']); ?>" maxlength="50">
</td>
<tr>
<td></td>
<td><?php
if (strlen($folder) > 50) {
echo '<div id="errormsg"> *Your new album name must be max 50 characters</div>';
}
?></td>
</tr>
</tr>
<tr>
<td id="editfill">Your Albums:</td>
<td>
<select name="folder_option" class="select">
<option></option>
<?php
$mysql_folder = mysql_query("SELECT `folder_name` FROM `files` WHERE `username` = '$usernameupload' AND `folder_name` > '' GROUP BY `folder_name` ORDER BY `folder_name` ASC");
while ($query_row = mysql_fetch_array($mysql_folder)) {
$filefolder = $query_row['folder_name'];
echo '<option value="' . $filefolder . '">' . $filefolder . '</option>';
}
?>
</select>
</td>
<tr>
<td></td>
<td></td>
</tr>
</tr>
<tr>
<td id="editfill">Description:</td>
<td><textarea name="description" id="description"><?php if (isset($_POST['submitupload'])) echo htmlentities($_POST['description']); ?></textarea></td>
<tr><td></td>
<td>
</td>
</tr>
</tr>
<tr>
<td></td>
<td><center><br><input type="submit" name="submitupload" id="submitupload" value="Upload"></center></td>
</tr>
</table>
</form>

Try this one to efficiently see if mkdir creation doesnt failed.
else folder and image surely will not be exist even it is added unto your database.
//previous code...
mkdir("files/$code");
mkdir("files/thumbs/$code");
//change to this...
if (!mkdir("files/$code", 0777, true)) {
die('Failed to create folders...');
}
if (!mkdir("files/thumbs/$code", 0777, true)) {
die('Failed to create sub folders...');
}

Related

Insert file and file type into mysql database with dynamic input field

I'm trying to insert multiple file into the database by using the dynamic input field created. Is there any way that can insert the file type into the database ? I have tried by using the code below but only the first file can be inserted.
PHP
if($q >= 0){
for($i=0; $i<=$q; $i++){
$certcheck = true;
$upload = end(explode(".", $_FILES['cert']['name'][$i]));
$imageType = $_FILES['cert']['type'][$i];
$fileType = array("png", "jpg", "jpeg", "pdf");
if (in_array(strtolower($upload), $fileType)) {
$cert1 = file_get_contents($_FILES['cert']['tmp_name'][$i]);
}
else {
$error = " The file is not an image or pdf. Please upload again";
$certcheck = false;
$_SESSION['error'] = $error;
}
$cert = $cert1;
$dtype = $imageType;
$sql3="INSERT INTO shorttest (cert,dtype) VALUES (:cert,:dtype)";
$query = $dbh->prepare($sql3);
$query->bindParam(':cert', $cert, PDO::PARAM_STR);
$query->bindParam(':dtype', $dtype, PDO::PARAM_STR);
$query->execute();
$msg = "Your Application Has Been Sent !";
}
}
}
Style
var q = 0;
function qualification() {
q++;
var copyContent= "<div class='row' name='rows' style='margin-top:-20px;'>";
copyContent= "<tr><td><input class='tableBody' type='file' id='cert"+q+"' name='cert[]'></td>";
copyContent += "<td><a href='javascript:void(0);' class='remove' style='cursor:pointer'><i class='material-icons' title='Delete item'>remove_circle_outline</i></a></td></tr></div>";
$('#tbl_qualification').append(copyContent);
document.getElementById("q").value = q;
}
HTML
<table id="tbl_qualification"style="margin-top:25px;margin-bottom:25px;">
<tr class="tableTitle">
<th style="width:200px"><center>Document</th>
<th style="width:20px;"></th>
</tr>
<tr>
<td><input class="tableBody" type="file" id="cert0" name="cert[]"></td>
</tr>
</table>
<div style="margin-right:-1200px">
<a onclick="qualification()" style="cursor:pointer"><i class="material-icons" title="Add item">add_circle_outline</i></a>
</div>
<input name="q" type="text" id="q" readonly hidden>

How to insert image into database and destination Folder using php and mysql?

I have created a test form just to try to Insert image into "student" table of mysql and "images" folder. But image not insert into database and images folder. The code below is just a test, I want to submit but it isntisn't.
**Mysql Database:**
CREATE TABLE STUDENT
(
STD_SL_NO INT(10) NOT NULL AUTO_INCREMENT,
STD_NAME VARCHAR(140) NOT NULL,
STD_FNAME VARCHAR(140) NOT NULL,
STD_MNAME VARCHAR(140) NOT NULL,
STD_BDATE DATE NOT NULL,
STD_GENDER VARCHAR(10) NOT NULL,
STD_RELIGIOUS VARCHAR(20) NOT NULL,
STD_CURR_ADDRESS TEXT NOT NULL,
STD_MOBILE CHAR(12),
STD_ROLL_NO INT(10) NOT NULL,
STD_PHOTO BLOB,
USER_NAME VARCHAR(50),
ENTRY_DATE TIMESTAMP (6),
PRIMARY KEY(STD_SL_NO, STD_ROLL_NO, STD_REG_NO)
)ENGINE=InnoDB;
**Form HTML & PHP:**
<!DOCTYPE html>
<html>
<head>
<title> Student Information Entry Form </title>
</head>
<body>
<form name="form1" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<table>
<tr>
<td><h4> Student Name</h4></td>
<td> <h5> <input type="text" name="t1" size="30"/></h5></td>
</tr>
<tr>
<td><h4> Student's Father Name</h4></td>
<td> <h5> <input type="text" name="t2" size="30"/></h5></td>
</tr>
<tr>
<td><h4> Student's Mother Name</h4></td>
<td> <h5> <input type="text" name="t3" size="30"/></h5></td>
</tr>
<tr>
<td><h4> Student's Birth Date</h4></td>
<td> <h5> <input type="date" name="t4" /></h5></td>
</tr>
<tr>
<td><h4> Student's Gender </h4></td>
<td>
<?php
$con=mysqli_connect("localhost", "root", "ew6wLoLOro", "result");
$sql=mysqli_query($con, "select gender_sl_no, gender_name from gender");
while($row=mysqli_fetch_array($sql))
{
echo '<table>
<input type="radio" name="t5" value='.$row['gender_name'].'
checked="checked"/>
'.$row['gender_name'].'
</table>';
}
?>
</td>
</tr>
<tr>
<td><h4> Please Select Your Religion</h4></td>
<td> <h5>
<div>
<select name="t6">
<option>Selection</option>
<?php
$sql=mysqli_query($con, "select religion_name from religion");
while($row=mysqli_fetch_array($sql))
{
?>
<option> <?php echo $row["religion_name"]; ?></option>
<?php
}
?>
</select> </div> </h5>
</td>
</tr>
<tr>
<td><h4>House No/Village,P.O/<br>Detail address except above </h4></td>
<td> <h5> <input type="text" name="t7" size="40" /></h5></td>
</tr>
<tr>
<td><h4>Entry Student Mobile No.</h4></td>
<td> <h5> <input type="text" name="t15" maxlength="11"
onpaste="return false;" onkeypress="StdMobile(event)">
<script>
function StdMobile(evt)
{
var anwar = String.fromCharCode(evt.which);
if(!(/[0-9]/.test(anwar)))
{
evt.preventDefault();
}
}
</script>
</h5></td>
</tr>
<tr>
<td><h4> Student Roll No. </h4></td>
<td> <h5> <input type="text" name="t23" maxlength="6"
onkeypress="StdRoll(event)" >
<script>
function StdRoll(evt)
{
var elaf=String.fromCharCode(evt.which);
if(!(/[0-9]/.test(elaf)))
{
evt.preventDefault();
}
}
</script>
</h5></td>
</tr>
<tr>
<td><h3> Student Photo</h3></td>
<td> <h5> <input type="file" name="file"/>
</h5></td>
</tr>
<tr>
<td> </td>
<td><input type ="submit" name="submit"/> </td>
</tr>
</table>
</form>
<?php
$con=mysqli_connect("localhost", "root", "ew6wLoLOro", "result");
if(!$con)
{
die('Could not connect:'.mysqli_connect_error());
}
if(isset($_POST['submit']))
{
$t1 = (isset($_POST['t1']) ? $_POST['t1']:null);
$t2 = (isset($_POST['t2']) ? $_POST['t2']:null);
$t3 = (isset($_POST['t3']) ? $_POST['t3']:null);
$t4 = (isset($_POST['t4']) ? $_POST['t4']:null);
$t5 = (isset($_POST['t5']) ? $_POST['t5']:null);
$t6 = (isset($_POST['t6']) ? $_POST['t6']:null);
$t7 = (isset($_POST['t7']) ? $_POST['t7']:null);
$t15 = (isset($_POST['t15']) ? $_POST['t15']:null);
$t23 = (isset($_POST['t23']) ? $_POST['t23']:null);
$file = (isset($_FILES['file']));
$file_name = $file['name'];
$file_type = $file ['type'];
$file_size = $file ['size'];
$file_path = $file ['tmp_name'];
if($file_name!="" && ($file_type="image/jpeg"||$file_type="image/png"||$file_type="image/gif")&& $file_size<=614400)
{
if(move_uploaded_file ($file_path,'images/'.$file_name))
{
$query="insert into student values(default, '$t1', '$t2', '$t3', '$t4', '$t5', '$t6', '$t7', '$t15', '$t23', '$file_name', default, default)";
$result = mysqli_query($con, $query);
if($result==true)
{
echo "File Uploaded";
}
}
}
}
?>
try with this code
Form
<form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
PHP Code"
<?php
include 'conf.php';
if ($_FILES["image"]["error"] > 0)
{
echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";
}
else
{
move_uploaded_file($_FILES["image"]["tmp_name"],"images/" . $_FILES["image"]["name"]);
echo"<font size = '5'><font color=\"#0CF44A\">SAVED<br>";
$file="images/".$_FILES["image"]["name"];
$sql="INSERT INTO eikones (auxon, path) VALUES ('','$file')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "<font size = '5'><font color=\"#0CF44A\">SAVED TO DATABASE";
}
mysql_close();
?>
Use this api. need little modify
/function to upload logo image/
public function upload_logo($filename,$temp_name,$filesize,$dir){
global $postClass;
$upload_size = imagesize*1424*1424;
$file_name = $filename;
if (!file_exists($dir))
{
mkdir($dir, 0777, true);
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $temp_name);
if($mime == 'image/jpeg' || $mime == 'image/png' || $mime == 'image/jpg' || $mime == 'image/JPG' || $mime == 'application/pdf')
{
if($filesize < $upload_size)
{
$temp = $temp_name;
$extention = explode('.',$file_name);
$name = rand(1,100).'_'.time().'.'.$extention[1];
if($mime == 'application/pdf'){
if(move_uploaded_file($temp,"$dir/$name")){
if(strpos($dir, '/') !== false){
$dir1 = explode('/', $dir);
$dir = $dir1[1];
}
else{
$dir =$dir;
}
return $dir.'/'.$name;
}
else{
return 1;
}
}
else{
$image = $postClass->compress($temp, "$dir/$name", 70);
//if(move_uploaded_file($temp,"$dir/$name"))
if($image)
{
if(strpos($dir, '/') !== false){
$dir1 = explode('/', $dir);
$dir = $dir1[1];
}
else{
$dir =$dir;
}
return $dir.'/'.$name;
}else{
return 1;
}
}
}else{
return 2;
}
}else{
return 3;
}
}

Save image file in database and images folder

i'm trying to save image in database and images folder in same time, the image it's saving in images folder but not in database can someone please help i don't know what im doing wrong.
add.php
<?php
if (!defined('WEB_ROOT')) {
exit;
}
$errorMessage = (isset($_GET['error']) && $_GET['error'] != '') ? $_GET['error'] : ' ';
?>
<script>
function getXMLHTTP() { //fuction to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCategory(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('catdiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<div class="content-box-header">
<h3>Add New Restaurant</h3>
</div>
<form action="processTopping.php?action=add" method="post" enctype="multipart/form-data" name="frmAddTopping" id="frmAddTopping">
<table width="100%" border="0" align="center" cellpadding="5" cellspacing="1" class="entryTable">
<tr>
<td width="150" class="label">Restaurant Name</td>
<td class="content"><input name="txtName" class="text-input large-input" type="text" id="txtName" /></td>
</tr>
<tr>
<td class="label">Restaurant Email</td>
<td class="content"><input name="txtEmail" class="text-input large-input" type="text" id="txtEmail" /></td>
</tr>
<tr>
<td class="label">Restaurant Phone</td>
<td class="content"><input name="txtPhone" class="text-input large-input" type="text" id="txtPhone" /></td>
</tr>
<tr>
<td class="label">Restaurant Address</td>
<td class="content"><input name="txtAddress" class="text-input large-input" type="text" id="txtAddress" /></td>
</tr>
<tr>
<td class="label">Restaurant Cuisine</td>
<td class="content"><input name="txtCuisine" class="text-input large-input" type="text" id="txtCuisine" /></td>
</tr>
<tr>
<td class="label">Restaurant Mini Order</td>
<td class="content"><input name="txtMini_order" class="text-input large-input" type="text" id="txtMini_order" /></td>
</tr>
<tr>
<td class="label">Restaurant Suburbs</td>
<td class="content"><input name="txtSuburbs" class="text-input large-input" type="text" id="txtSuburbs" /></td>
</tr>
<tr>
<td width="150" class="label">Restaurant Menu</td>
<td class="content"><input name="txtMenu" class="text-input large-input" type="text" id="txtMenu" /></td>
</tr>
<tr>
<td class="label">Restaurant Reviews</td>
<td class="content"><input name="txtReviews" class="text-input large-input" type="text" id="txtReviews" /></td>
</tr>
<tr>
<td class="label">Restaurant Logo</td>
<td class="content"><input name="txtLogo" class="text-input large-input" type="text" id="txtLogo" /></td>
</tr>
<tr>
<td class="label">Restaurant Takeaway Hours</td>
<td class="content"><input name="txtTakeawayHours" class="text-input large-input" type="text" id="txtTakeawayHours" /></td>
</tr>
<tr>
<td class="label">Restaurant Delivery Hours</td>
<td class="content"><input name="txtDeliveryHours" class="text-input large-input" type="text" id="txtDeliveryHours" /></td>
</tr>
<tr>
<td class="label">Restaurant Map</td>
<td class="content"><input name="txtMap" class="text-input large-input" type="text" id="txtMap" /></td>
</tr>
<tr>
<td class="label">Restaurant Promotions</td>
<td class="content"><input name="txtPromotions" class="text-input large-input" type="text" id="txtPromotions" /></td>
</tr>
<!-- <tr>
<td width="150" class="label">Image</td>
<td class="content"> <input name="fleImage" type="file" id="fleImage" class="box"> </td>
</tr>-->
<tr>
<td class="label" valign="middle">Images</td>
<td class="label">
<div id="main">
<table width="230" cellpadding="0">
<tr>
<td width="232" align="right">
<input type="file" name="fleImage[]" /></td>
</tr>
</table>
</div></td>
</tr>
</table>
<p align="center">
<input name="btnAddTopping" type="button" id="btnAddTopping" value="Add Restaurant" onClick="checkAddToppingForm();" class="button">
<input name="btnCancel" type="button" id="btnCancel" value="Cancel" onClick="window.location.href='index.php';" class="button">
</p>
</form>
processTopping.php
<?php
require_once '../../library/config.php';
require_once '../library/functions.php';
error_reporting(E_ALL);
checkUser();
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
case 'add' :
addTopping();
break;
case 'modify' :
modifyTopping();
break;
case 'delete' :
deleteTopping();
break;
default :
// if action is not defined or unknown
// move to main Topping page
header('Location: index.php');
}
function addTopping()
{
$name = $_POST['txtName'];
$email = $_POST['txtEmail'];
$phone = $_POST['txtPhone'];
$address = $_POST['txtAddress'];
$cuisine = $_POST['txtCuisine'];
$mini_order = $_POST['txtMini_order'];
$suburbs = $_POST['txtSuburbs'];
$menu = $_POST['txtMenu'];
$reviews = $_POST['txtReviews'];
$logo = $_POST['txtLogo'];
$takeaway_hours = $_POST['txtTakeawayHours'];
$delivery_hours = $_POST['txtDeliveryHours'];
$map = $_POST['txtMap'];
$promotions = $_POST['txtPromotions'];
$sql = "INSERT INTO restaurant_info(name, email, phone, address, cuisine, mini_order, suburbs, menu, reviews, logo, takeaway_hours, delivery_hours, map, promotions)
VALUES ('$name','$email','$phone','$address','$cuisine','$mini_order','$suburbs','$menu','$reviews','$logo','$takeaway_hours','$delivery_hours','$map','$promotions')";
dbQuery($sql);
header('Location: index.php');
}
//image
$uploadDir = '../../images/';
for($i=0;$i<count($_FILES["fleImage"]["name"]);$i++)
{
if($_FILES["fleImage"]["tmp_name"][$i] != '')
{
$image = $_FILES["fleImage"];
if (trim($image['tmp_name'][$i]) != '') {
$ext = substr(strrchr($image['name'][$i], "."), 1); //$extensions[$image['type']];
// generate a random new file name to avoid name conflict
$imagePath = md5(rand() * time()) . ".$ext";
list($width, $height, $type, $attr) = getimagesize($image['tmp_name'][$i]);
// make sure the image width does not exceed the
// maximum allowed width
if (LIMIT_PRODUCT_WIDTH && $width > MAX_PRODUCT_IMAGE_WIDTH) {
$result = createThumbnail($image['tmp_name'][$i], $uploadDir . $imagePath, MAX_PRODUCT_IMAGE_WIDTH);
$imagePath = $result;
} else {
$result = move_uploaded_file($image['tmp_name'][$i], $uploadDir . $imagePath);
}
if ($result) {
// create thumbnail
$thumbnailPath = md5(rand() * time()) . ".$ext";
$result = createFixThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, THUMBNAIL_WIDTH,THUMBNAIL_HEIGHT);
// create thumbnail failed, delete the image
if (!$result) {
unlink($uploadDir . $imagePath);
$imagePath = $thumbnailPath = '';
} else {
$thumbnailPath = $result;
}
} else {
// the product cannot be upload / resized
$imagePath = $thumbnailPath = '';
}
}
mysql_query("INSERT INTO restaurant_info(Rest_Logo)
VALUES ('$Rest_Logo')";
}
}
/*
Modify a Topping
*/
function modifyTopping()
{
$toppingId = (int)$_POST['hidToppingId'];
$name = $_POST['txtName'];
$email = $_POST['txtEmail'];
$phone = $_POST['txtPhone'];
$address = $_POST['txtAddress'];
$cuisine = $_POST['txtCuisine'];
$mini_order = $_POST['txtMini_order'];
$suburbs = $_POST['txtSuburbs'];
$menu = $_POST['txtMenu'];
$reviews = $_POST['txtReviews'];
$logo = $_POST['txtLogo'];
$takeaway_hours = $_POST['txtTakeawayHours'];
$delivery_hours = $_POST['txtDeliveryHours'];
$map = $_POST['txtMap'];
$promotions = $_POST['txtPromotions'];
$sql = "UPDATE restaurant_info
SET name='$name', email='$email', phone='$phone', address='$address', cuisine='$cuisine', mini_order='$mini_order', suburbs='$suburbs', menu='$menu', reviews='$reviews', logo='$logo', takeaway_hours='$takeaway_hours', delivery_hours='$delivery_hours', map='$map', promotions='$promotions'
WHERE rest_id = $toppingId";
dbQuery($sql);
header('Location: index.php');
}
/*
Remove a topping
*/
function deleteTopping()
{
if (isset($_GET['toppingId']) && (int)$_GET['toppingId'] > 0) {
$toppingId = (int)$_GET['toppingId'];
} else {
header('Location: index.php');
}
$sql = "DELETE FROM restaurant_info
WHERE rest_id = $toppingId";
dbQuery($sql);
header('Location: index.php');
}
?>
To save the file in database, you need to fetch content of file & save that in DB. You should choose datatype as longblob.
This can help you: http://forums.mysql.com/read.php?20,17671,27914
i just fixed it, i had to do some changes to the sql code.
<?php
require_once '../../library/config.php';
require_once '../library/functions.php';
error_reporting(E_ALL);
checkUser();
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
case 'add' :
addTopping();
break;
case 'modify' :
modifyTopping();
break;
case 'delete' :
deleteTopping();
break;
default :
// if action is not defined or unknown
// move to main Topping page
header('Location: index.php');
}
function addTopping()
{
if($_FILES['bgImg']['tmp_name']!='')
{
$srcFile = $_FILES['bgImg']['tmp_name'];
$size = $_FILES['bgImg']['size'];
if($size<5227520) //if file is less than 5MB
{
$ext = substr(strrchr($_FILES['bgImg']['name'], "."), 1);
$ext = strtolower($ext);
if (($ext != "jpg") && ($ext != "jpeg") && ($ext != "png") && ($ext != "gif"))
{
//print error message
print "<script>alert('Unknown File Format Detected')</script>";
print "<script>window.location='index.php'</script>";
exit;
}
else
{
$img_name = md5(rand() * time()) . ".$ext";
$dest = '../../testingImageIntoFolderAndDatabase/upload/';
$name = $_POST['txtName'];
$email = $_POST['txtEmail'];
$phone = $_POST['txtPhone'];
$address = $_POST['txtAddress'];
$cuisine = $_POST['txtCuisine'];
$mini_order = $_POST['txtMini_order'];
$suburbs = $_POST['txtSuburbs'];
$menu = $_POST['txtMenu'];
$reviews = $_POST['txtReviews'];
$logo = $_POST['txtLogo'];
$takeaway_hours = $_POST['txtTakeawayHours'];
$delivery_hours = $_POST['txtDeliveryHours'];
$map = $_POST['txtMap'];
$promotions = $_POST['txtPromotions'];
//copy new image
move_uploaded_file($_FILES['bgImg']['tmp_name'],$dest.$img_name);
dbQuery("insert into restaurant_info set Rest_Logo='$img_name', name='$name', email='$email', phone='$phone', address='$address', cuisine='$cuisine', mini_order='$mini_order', suburbs='$suburbs', menu='$menu', reviews='$reviews', logo='$logo', takeaway_hours='$takeaway_hours', delivery_hours='$delivery_hours', map='$map', promotions='$promotions'");
print "<script>window.location='index.php'</script>";
exit;
}
}
else
{
print "<script>alert('File Size Exceeded!')</script>";
print "<script>window.location='index.php'</script>";
exit;
}
}
}
/*
Modify a Topping
*/
function modifyTopping()
{
$toppingId = (int)$_POST['hidToppingId'];
$name = $_POST['txtName'];
$email = $_POST['txtEmail'];
$phone = $_POST['txtPhone'];
$address = $_POST['txtAddress'];
$cuisine = $_POST['txtCuisine'];
$mini_order = $_POST['txtMini_order'];
$suburbs = $_POST['txtSuburbs'];
$menu = $_POST['txtMenu'];
$reviews = $_POST['txtReviews'];
$logo = $_POST['txtLogo'];
$takeaway_hours = $_POST['txtTakeawayHours'];
$delivery_hours = $_POST['txtDeliveryHours'];
$map = $_POST['txtMap'];
$promotions = $_POST['txtPromotions'];
$sql = "UPDATE restaurant_info
SET name='$name', email='$email', phone='$phone', address='$address', cuisine='$cuisine', mini_order='$mini_order', suburbs='$suburbs', menu='$menu', reviews='$reviews', logo='$logo', takeaway_hours='$takeaway_hours', delivery_hours='$delivery_hours', map='$map', promotions='$promotions'
WHERE rest_id = $toppingId";
dbQuery($sql);
header('Location: index.php');
}
/*
Remove a topping
*/
function deleteTopping()
{
if (isset($_GET['toppingId']) && (int)$_GET['toppingId'] > 0) {
$toppingId = (int)$_GET['toppingId'];
} else {
header('Location: index.php');
}
$sql = "DELETE FROM restaurant_info
WHERE rest_id = $toppingId";
dbQuery($sql);
header('Location: index.php');
}
?>

HiddenField posting value without name

This is weird, and ive never seen this before. Im using post to post values back to the same page for processing. Everything is working fine until I try to use a hidden field to post values. Using the same convention ive used a million times before. The odd thing is that its not posting using the name supplied, its just using hiddenField as the name. Here is the code
<input name="eid" type="hidden" id="eid" value="<? print $_GET['eid']; ?>" />
And im using this to figure it out
print_r($_POST);
This is the result
[hiddenField] => 6
Now, its posting the value, and its posting the correct value that is put into the hidden field before its submitted, but for some reason that I cant seem to figure out, its not using the name attribute that I set in HTML to identify it. All my other values are using there posted names. Any insight would be greatly appreciated as I do not wish to have to deal with an awkward array of hiddenFields later on.
Edit: Here is the rest of the code for the page (pertinent parts)
<?
if (isset($_POST['Submit']))
{
print "<p>EID: " . $_POST['hiddenField'] . "</p>";
$eid = $_POST['hiddenField'];
$name = $_POST['name'];
$email = $_POST['email'];
$ncount = count($name);
$ecount = count($email);
$hash = uniqid() . "-" . count($name);
if ($ncount == $ecount)
{
$test = true;
for ($i = 0; $i < $ncount; $i++)
{
if ($name[$i] == "" || $email[$i] == "")
{
$test = false;
}
}
if ($test)
{
$tickets[] = array();
for ($i = 0; $i< $ncount; $i++)
{
$unique = false;
while (!$unique)
{
$tickets[$i] = generateCode();
$check_query = "SELECT id FROM ticket WHERE ticket_number='" . $tickets[$i] . "'";
if ($stmt = $mysqli->prepare($check_query))
{
$stmt->execute();
$stmt->store_result();
$count = $stmt->num_rows;
$stmt->close();
if ($count == 0)
{
$unique = true;
} else {
print "<p>Not unique</p>";
}
} else {
print "<p>Failed to work database</p>";
}
}
if ($unique == true)
{
$query = "INSERT INTO ticket (`ticket_number`, `event_id`, `name`, `email`,`date_created`, `hash`) VALUES (?,?,?,?,NOW(),?)";
print "<p>Ticket #" . $tickets[$i] . " Event Id: " . $eid . " Name: " . $name[$i] . " Email: " . $email[$i] . " Hash: " . $hash . "</p>";
if ($stmt = $mysqli->prepare($query))
{
$stmt->bind_param('sisss', $tickets[$i], $eid, $name[$i], $email[$i], $hash);
$stmt->execute();
$number = $stmt->affected_rows;
} else {
print "<p>Could not insert into DB because " . $stmt->error . "</p>";
}
}
}
}
}
}
<form action="register.php" method="post">
<table width="896" border="0">
<?
for($i = 0; $i<$_GET['quant']; $i++)
{
?> <tr>
<td><strong>Attendee <? print $z = $i+1; ?></strong></td>
<td> </td>
</tr>
<tr>
<td width="215">Name</td>
<td width="671"><label for="name"></label>
<input type="text" name="name[]" id="name" /></td>
</tr>
<tr>
<td>Email Address</td>
<td><input type="text" name="email[]" id="name2" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<?
}
}
?>
<tr>
<td><input name="eid" type="hidden" id="eid" value="<? print $_GET['eid']; ?>" /></td>
<td><input type="submit" name="Submit" id="Submit" value="Submit" /></td>
</tr>
</table>
</form>

How do I fix a PHP script that isn't processing a form?

On a script of mine, it fails when I click the "Update" button. Basically, it will not check if the input fields are entered in correctly. In addition, if the form is filled out correctly, it will not actually update the information. In short, processing the error checks and update code aren't working. Here is my script.
<?php
error_reporting (E_ALL ^ E_NOTICE);
session_start();
$userid = $_SESSION['userid7906'];
$username = $_SESSION['username7906'];
$email = $_SESSION['email7906'];
$one = $_SESSION['yes7906'];
$zero = $_SESSION['no7906'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Profile Settings</title>
<meta http-equiv="Content=Type" content="text/html; charset=utf-8" />
<LINK REL=StyleSheet HREF="./css/profile_settings.css" TYPE="text/css" MEDIA=screen>
</head>
<body>
<?php
$info = $_COOKIE['user7906']." <a href='./logout.php'>Log Out</a> <a href='./memberpage.php'>Home</a> <b><a href='./profile.php? user=$_COOKIE[user7906]'>Profile</a></b> > Edit <a href='./search.php'>User Search</a> <a href='./account.php'>Account</a> <br/><hr/>";
$info2 = $_COOKIE['user7906']." <a href='./logout.php'>Log Out</a> <a href='./memberpage.php'>Home</a> <b><a href='./profile.php?user=$username'>Profile</a></b> > Edit <a href='./search.php'>User Search</a> <a href='./account.php'>Account</a> <br/><hr/>";
if (isset($_COOKIE['user7906']) && isset($_COOKIE['pass7906']) && isset($_COOKIE['email7906'])) {
echo $info."<br/>";
if (isset($_COOKIE['no7906'])) {
header("Location: ./profile.php?user=$_COOKIE[user]");
}
else {
require('./connect.php');
$fgh = mysql_query("SELECT * FROM `users` WHERE username='$_COOKIE[user7906]'");
$abc = mysql_num_rows("$fgh");
if ($abc !== 0) {
$osu = mysql_fetch_assoc($fgh);
$harv = $osu['id'];
$usr = $osu['username'];
$et = mysql_query("SELECT * FROM `profiles` WHERE users_id='$harv'");
$elm = mysql_num_rows($et);
if ($elm !== 0) {
$c = mysql_fetch_assoc($et);
$mm = $c['email'];
$bio = $c['about'];
$fnm = $c['first_name'];
$lnm = $c['last_name'];
$lc4 = $c['location'];
echo "<center><b>Profile Settings</b></center><br/><br/>";
if (isset($_POST['submit']) === true) {
$value=$_REQUEST['fn'];
}
else {
$value=$fnm;
}
if (isset($_POST['go']) === true) {
$value=$_REQUEST['fn'];
$value2=$_REQUEST['ln'];
$value3=$_REQUEST['email'];
$value4=$_REQUEST['about'];
$value5=$_REQUEST['locate'];
}
else {
$value=$fnm;
$value2=$lnm;
$value3=$mm;
$value4=$bio;
$value5=$lc4;
}
?><center>
<form action='./profile_settings.php' method='POST' name='lp' />
<table>
<tr>
<td>First Name:</td>
<td><input type='text' name='fn' value="<?php echo $value; ?>" /><br/></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type='text' name='ln' value="<?php echo $value2; ?>" /><br/></td>
</tr>
<tr>
<td>Email:</td>
<td><input type='text' name='email' value="<?php echo $value3; ?>" /><br/></td>
</tr>
<tr>
<td>About:</td>
<td><input type='text' name='about' value="<?php echo $value4; ?>" /><br/></td>
</tr>
<tr>
<td>Location:</td>
<td><input type='text' name='locate' value="<?php echo $value5; ?>" /><br/></td>
</tr>
</table>
<center><input type='submit' name='go' value='Update' /> <?php echo "<a href='./profile.php?user=$_COOKIE[user7906]'>Cancel</a>"; ?></center>
</center></form>
<?php
$go = $_POST['go'];
$fn = $_POST['fn'];
$ln = $_POST['ln'];
$em = trim(strtolower($_POST['email']));
$ab = $_POST['about'];
$lc = $_POST['locate'];
if (isset($go)==='Update') {
if ((!empty($fn)) && (!empty($ln)) && (!empty($em)) && (!empty($ab)) && (!empty($lc)) && (strlen($em) > 6) && (strstr($em, "#")) == false && (strstr($em, ".")) == false) {
require("./connect.php");
$update = mysql_query("UPDATE `profiles` SET first_name='$fn' WHERE users_id='$harv' ");
$update2 = mysql_query("UPDATE `profiles` SET last_name='$ln' WHERE users_id='$harv' ");
$update3 = mysql_query("UPDATE `profiles` SET email='$em' WHERE users_id='$harv' ");
$update4 = mysql_query("UPDATE `profiles` SET about='$ab' WHERE users_id='$harv' ");
$update5 = mysql_query("UPDATE `profiles` SET location='$lc' WHERE users_id='$harv' ");
echo '<br/>Profile updated successfully';
}
elseif (!isset($_POST)) {
echo '<br/><center>Please fill out this form.</center>';
}
elseif (isset($fn)==='') {
echo '<br/><center>Enter your first name.</center>';
}
elseif (isset($ln)==='') {
echo '<br/><center>Enter your last name.</center>';
}
elseif (isset($em)==='') {
echo '<br/><center>Enter your email.</center>';
}
elseif ((strlen($em) < 7) || (strstr($em, "#")) === false || (strstr($em, ".")) === false) {
echo '<br/><center>Invalid email</center>';
}
elseif (isset($ab)==='') {
echo '<br/><center>Write something about yourself.</center>';
}
elseif (isset($lc)==='') {
echo '<br/><center>Enter your location.</center>';
}
else {
echo '<center>An error has occured.</center>';
}
}
}
else {
header("Location: ./profile.php?user=$_COOKIE[user7906]");
}
}
else {
echo '<center>An error has occured.</center>';
}
}
}
elseif(isset($username) && isset($userid) && isset($email)) {
echo $username.$info2."<br/>";
require('./connect.php');
$fgh = mysql_query("SELECT * FROM `users` WHERE username='$username'");
$abc = mysql_num_rows($fgh);
if ($abc !== 0) {
$osu = mysql_fetch_assoc($fgh);
$harv = $osu['id'];
$usr = $osu['username'];
$et = mysql_query("SELECT * FROM `profiles` WHERE users_id='$harv'");
$elm = mysql_num_rows($et);
if ($elm !== 0) {
$c = mysql_fetch_assoc($et);
$mm = $c['email'];
$bio = $c['about'];
$fnm = $c['first_name'];
$lnm = $c['last_name'];
$lc4 = $c['location'];
echo "<center><b>Profile Settings</b></center><br/><br/>";
if (isset($_POST['go']) === true) {
$value=$_REQUEST['fn'];
$value2=$_REQUEST['ln'];
$value3=$_REQUEST['email'];
$value4=$_REQUEST['about'];
$value5=$_REQUEST['locate'];
}
else {
$value=$fnm;
$value2=$lnm;
$value3=$mm;
$value4=$bio;
$value5=$lc4;
}
?>
<form action='./profile_settings.php' method='POST' name='lp' /><center>
<table>
<tr>
<td>First Name:</td>
<td><input type='text' name='fn' value="<?php echo $value; ?>" /><br/></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type='text' name='ln' value="<?php echo $value2; ?>" /><br/></td>
</tr>
<tr>
<td>Email:</td>
<td><input type='text' name='email' value="<?php echo $value3; ?>" /><br/></td>
</tr>
<tr>
<td>About:</td>
<td><input type='text' name='about' value="<?php echo $value4; ?>" /><br/></td>
</tr>
<tr>
<td>Location:</td>
<td><input type='text' name='locate' value="<?php echo $value5; ?>" /><br/></td>
</tr>
</table>
<center><input type='submit' name='go' value='Update' /> <?php echo "<a href='./profile.php?user=$username'>Cancel</a>"; ?></td></center>
</center></form>
<?php
$go = $_POST['go'];
$fn = $_POST['fn'];
$ln = $_POST['ln'];
$em = trim(strtolower($_POST['email']));
$ab = $_POST['about'];
$lc = $_POST['locate'];
if (isset($go)==='Update') {
if ((!empty($fn)) && (!empty($ln)) && (!empty($em)) && (!empty($ab)) && (!empty($lc)) && (strlen($em) > 6) && (strstr($em, "#")) == false && (strstr($em, ".")) == false) {
require("./connect.php");
$update = mysql_query("UPDATE `profiles` SET first_name='$fn' WHERE users_id='$userid' ");
$update2 = mysql_query("UPDATE `profiles` SET last_name='$ln' WHERE users_id='$userid' ");
$update3 = mysql_query("UPDATE `profiles` SET email='$em' WHERE users_id='$userid' ");
$update4 = mysql_query("UPDATE `profiles` SET about='$ab' WHERE users_id='$userid' ");
$update5 = mysql_query("UPDATE `profiles` SET location='$lc' WHERE users_id='$userid' ");
echo '<br/>Profile updated successfully';
}
elseif (!isset($_POST)) {
echo '<br/><center>Please fill out this form.</center>';
}
elseif (isset($fn)==='') {
echo '<br/><center>Enter your first name.</center>';
}
elseif (isset($ln)==='') {
echo '<br/><center>Enter your last name.</center>';
}
elseif (isset($em)==='') {
echo '<br/><center>Enter your email.</center>';
}
elseif ((strlen($em) < 7) || (strstr($em, "#")) === false || (strstr($em, ".")) === false) {
echo '<br/><center>Invalid email</center>';
}
elseif (isset($ab)==='') {
echo '<br/><center>Write something about yourself.</center>';
}
elseif (isset($lc)==='') {
echo '<br/><center>Enter your location.</center>';
}
else {
echo '<center>An error has occured.</center>';
}
}
}
else {
header("Location: ./profile.php?user=$username");
}
}
else {
echo '<center>An error has occured.</center>';
}
}
else {
echo "<center>Please <a href='./login.php'log in</a> for access to this page.</center>";
}
?>
if (isset($go)==='Update') {
isset() returns either true or false, not a string.

Categories