I've got this upload form and would like to keep the selected option from the dropdown in the session in order to show the last selection after submitting, e.g. i choose the option 'colour' und after submitting colour is still selected in the dropdown.
I echo $_SESSION['testname'] (just before the first radio button) and it gives me back "colour", but in the option-tag where i'd like to echo 'selected' if "colour" was the last selection, it returns nothing! what am i missing?
<?php
session_start();
if(isset($_POST['kategorie'])) {
$_SESSION['testname']=$_POST['kategorie']; }
?>
<?php
$con = mysqli_connect("localhost","Melvin","") or die ("could not connect to server: " . mysqli_connect_error($con));
mysqli_select_db($con, "galerie") or die ("Could not connect to database: " . mysqli_error($con));
if(isset($_POST['submit'])){
$name = $_FILES['file']['name'];
$sub_name = substr($name, 0, -4);
$img_ext = ".jpg";
$tmp_name = $_FILES['file']['tmp_name'];
$location = '_images/_galerie/';
$target = '_images/_galerie/' .$name;
if(move_uploaded_file($tmp_name,$location.$name)){
echo "file uploaded";
$nam = $_POST['nam'];
$kategorie = $_POST['kategorie'];
$size = $_POST['size'];
if ($size == 'thumb') {
// add "thumb" between filename and extension
$extension_pos = strrpos($target, '.'); // find position of the last dot, so where the extension starts
$thumb = substr($target, 0, $extension_pos) . '_thumb' . substr($target, $extension_pos);
$query = mysqli_query($con , "INSERT INTO images(img_name,img_title,img_cat,img_size)VALUES('".$thumb."','$nam','$kategorie','$size')");
} else {
$query = mysqli_query($con , "INSERT INTO images(img_name,img_title,img_cat,img_size)VALUES('".$target."','$nam','$kategorie','$size')");
}
function renameImg() {
$name = $_FILES['file']['name'];
$target = '_images/_galerie/' .$name;
$extension_pos = strrpos($target, '.');
$thumb = substr($target, 0, $extension_pos) . '_thumb' . substr($target, $extension_pos);
rename($target, $thumb);
//echo $name . " replaced with " . $thumb;
};
renameImg();
} else {
echo "file not uploaded";
}
}
?>
<div style="margin:20px 0 40px 0;">
<form action="upload.php" method="POST" enctype="multipart/form-data">
Upload: <input type="file" name="file">
Title: <input type="text" name="nam" value="Tattoo Gallery">
Category: <select name="kategorie" id="selectKat">
<option value="black" <?php if(isset($_SESSION['kategorie']) == "black") { echo ' selected';} ?>>Black and white</option>
<option value="colour" <?php if(isset($_SESSION['kategorie']) == "colour") { echo ' selected';} ?>>Colour</option>
</select>
<br>
<?php
echo $_SESSION['testname'];
?>
<input type="radio" name="size" value="full" id="regularRadio" checked="checked">
<label for="regularRadio">Full size</label>
<br>
<input type="radio" name="size" value="thumb" id="thumbRadio">
<label for="thumbRadio">Thumbnail</label>
<br>
<input type="submit" name="submit">
</form>
</div>
<?php
$result = mysqli_query($con, "SELECT * FROM images WHERE img_size='thumb'");
while($row = mysqli_fetch_array($result)){
echo "<img src=".$row['img_name'] . " class='thumbnails' style='display:inline;float:left;'>";
}
?>
You must not use the isset() function. This function return True or False.
You only have to compare the value of $_POST['kategorie'] or $_SESSION['testname'] (as I see) with your text ("color" or "black"), like this :
if ($_SESSION['kategorie'] == "black") { echo ' selected'; }
Related
I have a php file named "add_report" with a form inside it. All my inputs are running, i can input data into my database, but everytime I use the select-option. my database accepts it as null. Why is that?
This is my form "add_report.php"
<div class="wrapper">
<form action="add_report_backend.php" method="post">
<input type="hidden" name="id">
<label>Agency: </label> <input class="input1" type="text" name="agency" value="CAAP" required readonly><br>
<label>File Name: </label> <input class="input2" type="text" name="filename" placeholder="file.pdf/xlsx/xls/docx" required autofocus><br>
<label>File Type: </label> <select name="myselectbox">
<option name="myoption1" value="myoption1">pdf</option>
<option name="myoption2" value="myoption2">excel</option>
<option name="myoption3" value="myoption3">word</option>
</select><br>
<label>Date: </label> <input class="input4" type="Date" name="date" required><br>
<input class="submit-btn" type="submit" name="insert" value="Save">
</form>
</div>
And this another php file "add_report_backend.php"
<?php
if(isset($_POST['insert']))
{
try {
$pdoConnect = new PDO("mysql:host=localhost;dbname=annualdb","root","");
$pdoConnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
$id = $_POST['id'];
$Agency = $_POST['agency'];
$FName = $_POST['filename'];
$FType = $_POST['filetype'];
$Date = $_POST['date'];
$pdoQuery = "INSERT INTO `company_report`(`agency`, `filename`, `filetype`, `date`) VALUES (:Agency,:FName,:FType,:Date)";
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoExec = $pdoResult->execute(array(":Agency"=>$Agency,":FName"=>$FName,":FType"=>$FType, ":Date"=>$Date));
if($pdoExec)
{
$pdoQuery = 'SELECT * FROM company_report';
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoResult->execute();
while ($row = $pdoResult->fetch()){
echo $row['id'] . " | " .$row['agency'] . " | " . $row['filename'] . " | " . $row['filetype'] . " | " . $row['date'];
}
header("Location: ../agencies/company.php");
exit;
} else {
echo 'Data Not Inserted';
}
}
$pdoConnect = null;
?>
The HTML name attribute and the $_POST name should be the same.
You need to change
$FType = $_POST['filetype'];
by
$FType = $_POST['myselectbox'];
Change $FType = $_POST['filetype']; to $FType = $_POST['myselectbox'];
So the main problem is that I can't seem to move the images to my designated folder. I have this database that records the name and directory. It seems to work well. It's only the images that fail to move to the folder.
Here's the HTML code:
<div class="form-group" align="left">
<label for="aialbum">Album:</label>
<select class="form-control" id="aialbum" name="aialbum">
<?php
$query = "SELECT * FROM cms_albums";
$showalbums = mysqli_query($con, $query);
while($getalbum = mysqli_fetch_array($showalbums))
{
$album = $getalbum['album_name'];
echo "<option value='$album'>$album</option>";
}
?>
</select>
<br><label for="aipicture">Image/s:</label>
<div class="form-group">
<input type='file' name='aipicture[]' id='aipicture[]' multiple>
</div>
</div>
<div align="right">
<input class="btn btn-default" type='submit' name='aisubmit' value='Submit'>
</div>
Here's my PHP code: (Update)
if(isset($_POST['aisubmit']))
{
$aialbum = $_POST['aialbum'];
$aipicture = $_POST['aipicture'];
$filecount = count($aipicture);
for($i=0; $i<$filecount; $i++)
{
$temp_name = $_FILES[$aipicture[$i]]['tmp_name'];
$org_name = $_FILES[$aipicture[$i]]['name'];
$path = "../img";
move_uploaded_file($temp_name, $path);
$sql = "INSERT INTO cms_album_photos (album_name, picture) VALUES ('$aialbum', 'img/$aipicture[$i]')";
mysqli_query($con, $sql);
}
echo '<script type="text/javascript">';
echo 'window.location.href="home.php";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url=home.php" />';
echo '</noscript>'; exit;
}
Do like this
$target_Path = "asd/".basename( $_FILES['fileToUpload']['name']);
move_uploaded_file( $_FILES['fileToUpload']['tmp_name'], $target_Path );
improve your code from this
$temp_name = $_FILES[$aipicture[$i]]['tmp_name'];
$org_name = $_FILES[$aipicture[$i]]['name'];
To this
$temp_name = $_FILES[$aipicture]['tmp_name'][$i];
$org_name = $_FILES[$aipicture]['name'][$i];
Hope this help!
I'm sorry if this is a repost. But I have seen many questions without finding the right answer
i'm trying to upload multiple files + some information , but if i submit my form with 2 images it goes ok and the script runs perfect when i upload more then 2 or 3 files i get undefined indexs of all the form elements .
up.php
/////// Random name generator ////////
function random_name($length) {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
//sql//
require("sql.php");
//////////
//!!! some vars !!!//
//
$total = count($_FILES['pimages']['name']);
//
$foldername = random_name(15);
$target_dir = "../images/projects/".$foldername."/";
$target_file = $target_dir . basename($_FILES["icon"]["name"]);
$uploadyes = 1;
$imageType = pathinfo($target_file,PATHINFO_EXTENSION);
$saveicon = $target_dir . "icon." .$imageType;
/////submited form vars /////
$linkedid = $_POST['lid'];
$date = date("y.m.d H:i:s");
$name = $_POST['projectname'];
$loc = $_POST['location'];
$type = $_POST['type'];
$des = $_POST['des'];
$precara = $_POST['cara'];
$client = $_POST['client'];
$col = $_POST['cost'];
$bua = $_POST['builtup'];
////////////////cara slice /////////////
$caraxarray = explode("," , $precara);
$cara = base64_encode(serialize($caraxarray));
echo $imageType ;
///////////////////////// Start of the upload check ////////////////////
if(isset($_POST['submit']) && !empty($name)) {
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
}
// Check if $uploadyes is set to 0 by an error
if (!isset($_POST['submit'])) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
mkdir($target_dir);
if (move_uploaded_file($_FILES["icon"]["tmp_name"], $saveicon)) {
//////////////////////////..........................//////////////////
// Loop through each file
$imgext = array();
for($i=0; $i<=$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['pimages']['tmp_name'][$i];
$x = $i + 1 ;
if ($tmpFilePath != ""){
//Setup our new file path
$pimgex = $_FILES['pimages']['name'][$i];
$pimageType = pathinfo($pimgex,PATHINFO_EXTENSION);
$newFilePath = $target_dir ."img".$x.".".$pimageType;
array_push($imgext , "$newFilePath");
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo "yeaaaaaah";
}
}
}
$str = serialize($imgext);
$sql1 = "INSERT INTO projects (date, name, type, location, icon, imgext, folder, linkedid)
VALUES ('$date', '$name','$type', '$loc', '$saveicon' , '$str', '$foldername', '$linkedid')";
$sql2 = "INSERT INTO projectdetails (proname, prolocation, prodes, procara, client, col, builtarea, linkedid)
VALUES ('$name', '$loc','$des', '$cara', '$client' , '$col', '$bua', '$linkedid')";
mysqli_query($conn ,$sql1);
mysqli_query($conn ,$sql2);
mysqli_close($conn);
/////////////////...........................////////////////////////
header("location:cp.php");
} else {
echo "Sorry, there was an error uploading your file.";
}
}
projectsuploader.php
$lkid = random_name(8);
$tlink = random_name(6);
require("sql.php");
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql1 = "SELECT id, date, name, type, location FROM projects";
$sql2 = "SELECT id, titleen FROM projectsnav";
$result = mysqli_query($conn, $sql1);
$types = mysqli_query($conn, $sql2);
//mysqli_close($conn);
?>
<!DOCTYPE html>
<html>
<h2>Projects Page</h2>
<h5>projects</h5>
<table>
<tr>
<td>#</td>
<td>Date & Time</td>
<td>Project name</td>
<td>Project type</td>
<td>Project location</td>
<!--<td>View</td>
<td>Edit</td>-->
<td>Remove</td>
</tr>
<?php
if (mysqli_num_rows($result) > 0) {
// output data of each row .$row["id"]
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".$row["id"]."</td>";
echo "<td>".$row["date"]."</td>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["type"]."</td>";
echo "<td>".$row["location"]."</td>";
echo "<td><a href='../del.php?id=".$row['id']."'>Remove</a></td> </tr>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</table>
<h4 id="addproject">Add Project</h3>
<h4 id="addtype">Add Type </h4>
<div id="frontlayer">
<div id="addpro">
<h2 style="text-align:center;"> add project </h2>
<form method="POST" action="up.php" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="50000000">
id:<input type="text" name="lid" value="<?php echo $lkid ; ?>" readonly> <br>
project name:<input type="text" name="projectname"><br>
Type:<select name="type">
<?php
if (mysqli_num_rows($types) > 0){
while($navrow = mysqli_fetch_assoc($types)) {
echo "<option value='".$navrow['titleen']."'>".$navrow['titleen']." </option>";
}
}else{
echo "<option>PLEASE ADD TYPES TO DATABASE FIRST!!!!ERROR 0 TYPES IN DATABASE</option>";
}
mysqli_close($conn);
?>
</select>
<br>
location:<input type="text" name="location"><br>
icon:<input type="file" name="icon" id="icon"><br>
images:<input type="file" name="pimages[]" id="pimages" multiple><br>
<input type="hidden" name="sendfiles" value="Send Files" />
<!--
------//////////////------
------//////////////------
------//////////////------
-->
description:<input type="text" name="des"><br>
caracteristic:<input type="text" name="cara" data-role="tagsinput"><br>
client:<input type="text" name="client"><br>
Collaborator:<input type="text" name="cost"><br>
Gross Area:<input type="text" name="builtup"><br>
<input type="submit" value="Upload" name="submit">
</form>
</div>
Sorry if it is bad writed i\m begginer , Thanks in advance for anyhelp
The problem were that there was a big file (4mb image) and php was not able to post this size of an image so you have to resize your image before upload ..
and big thanks for Felippe Duarte.
I use HTML form to insert data to a database table. What I want to do is to display the data I inserted using the HTML form. I use associative arrays to get the right data from the database. But I can only display only one row from the table. I don't know why my code doesn't display the other data I inserted.
Here is my code:
<?php
$part_insert_message = "";
enter code here
session_start();
$inserted_parts = array();
$part_inserted_id;
if(isset($_POST['submit'])) {
require "/Basics/Mysql_Connect/mysql_connect.php";
$sql="INSERT INTO Parts (SKU, Part, Description, Quantity, Price)
VALUES
('$_POST[sku]', '$_POST[categories]', '$_POST[description]', '$_POST[quantity]', '$_POST[price]')";
$result = mysqli_query($con, $sql);
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
$part_inserted_id = mysqli_insert_id($con);
$inserted_parts[$part_inserted_id] = $part_inserted_id;
// store session data
$_SESSION['views']= $inserted_parts;
$part_insert_message = "ID: " . $part_inserted_id . " Part: " . $_POST['sku'];
mysqli_close($con);
}
?>
<?php
// This block grabs the whole list for viewing
$product_list = "";
if(isset($_SESSION['views'])){
$inserted_parts = $_SESSION['views'];
}
if(!empty( $inserted_parts )) {
require "/Basics/Mysql_Connect/mysql_connect.php";
foreach($inserted_parts as $key => $value){
$sql = "SELECT * FROM Parts WHERE PartID='$key'";
$result = mysqli_query($con, $sql);
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
$productCount = mysqli_num_rows($result); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($result)){
$partID = $row["PartID"];
$sku = $row["SKU"];
$part = $row["Part"];
$description = $row["Description"];
$quantity = $row["Quantity"];
$price = $row["Price"];
$product_list .= "Product ID: $partID - <strong>$sku</strong> - $$price - <em>Part $part</em> <a href='Add_Delete_Part.php?deleteid=$partID'>delete</a><br />";
}
}else {
$product_list = "You have no products listed in your store yet";
}
}
mysqli_close($con);
}
?>
<?php
require "/Basics/Mysql_Connect/mysql_connect.php";
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete product with ID of ' . $_GET['deleteid'] . '? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// remove item from system and delete its picture
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = "DELETE FROM Parts WHERE PartID='$id_to_delete'";
$result = mysqli_query($con, $sql);
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
// unlink the image from server
// // Remove The Pic -------------------------------------------
// $pictodelete = ("../inventory_images/$id_to_delete.jpg");
// if (file_exists($pictodelete)) {
// unlink($pictodelete);
// }
header("location: Add_Delete_Part.php");
exit();
}
mysqli_close($con);
?>
<html>
<body>
<div>
<h2>Part</h2>
<form action="Add_Delete_Part.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">
SKU#: <input type="text" name="sku"><br>
Part: <select name="categories">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select><br>
Description: <input type="text" name="description"><br>
Quantity: <input type="text" name="quantity"><br>
Price: <input type="text" name="price"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php echo $part_insert_message; ?>
<h3>Fits:</h3>
<?php echo $product_list; ?>
<!--<form action="Add_Images.php" method="post">
Select images: <input type="file" name="img" multiple><input type="submit" value="Upload">
</form>
-->
</div>
</body>
</html>
Here is my solution to the problem that doesn't work. It's made up of four different PHP files one with the form, one to update the database, one to change the image header so it looks correctly and last to display everything.
//create form
<h3>create person</h3>
<form action="create.php" method="post" enctype="multipart/form-data">
name:<input type="text" name="personname" value=""/>
info:<input type="text" name="personinfo" value=""/>
<br />
<br />
image:<input type="file" name="image" />
<input type="submit" name="submit" value="upload" />
</form>
<?php
$people = mysql_query("SELECT * FROM people", $connection);
if(!$people){
die("Failed: " . mysql_error());
}
while ($person = mysql_fetch_array($people)){
echo "<h1>{$person["name"]}</h1>";
echo "<p>{$person["info"]}</p>";
echo "<p>{$person["id"]}</p>";
echo "<P>{$person["img_name"]}</p>";
echo "<img src=getimage.php?id=" . urlencode($person["id"]) . ">";
echo "<br />Modify User";
echo " ";
echo "Delete User";
}
?>
//creates image
<?php include 'includes/connection.php'; ?>
<?PHP
$name = $_POST['personname'];
$info = $_POST['personinfo'];
$img_name = addslashes($_FILES['image']['name']);
$image = imagecreatefromjpeg($_FILES['image']['tmp_name']);
$size = addslashes($_FILES['image']['size']);
$type = addslashes($_FILES['image']['type']);
$size2 = getimagesize($temp);
$width = $size2[0];
$height = $size2[1];
$newwidth = 100;
$ratio = $newwidth/$width;
$newheight = round($height * $ratio);
$new = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($new, $image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($image);
mysql_query("INSERT INTO people (`id`,`name`,`info`,`image`,`img_name`)
VALUES (NULL, '$name','$info','$new','$img_name')")or die(mysql_error);
header ('Location: adminarea.php?linkid=1');
?>
//display image
<?php include 'includes/connection.php'; ?>
<?php
$people = mysql_query("SELECT * FROM people", $connection);
if(!$people){
die("Failed: " . mysql_error());
}
while ($person = mysql_fetch_array($people)){
echo "<h1>{$person["name"]}</h1>";
echo "<p>{$person["info"]}</p>";
echo "<p>{$person["id"]}</p>";
echo "<P>{$person["img_name"]}</p>";
echo "<img src=getimage.php?id=" . urlencode($person["id"]) . ">";
echo "<br />Modify User";
echo " ";
echo "Delete User";
}
?>
//change header of image
<?php Include 'includes/connection.php';?>
<?php
$id = addslashes($_GET['id']);
$image = mysql_query("SELECT * FROM people WHERE id = $id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
?>