I want to create a from to change the image for a record in a table. When I load in the image to the form the image appears to be there but the file selector control text says "no file chosen". What am I doing wrong?
<html>
<body>
<main>
<form name="EditForm" action="test-save-edit.php" method="POST" enctype="multipart/form-data">
<?php
$post_id = trim($_GET["id"]);
require_once "config.php";
try{
$sql1 = "select picture from images where post_id=:post_id";
if($stmt1 = $pdo->prepare($sql1)){
$stmt1->bindParam(":post_id", $post_id, PDO::PARAM_INT );
if($stmt1->execute()){
if($stmt1->rowCount() > 0){
$i = 0;
while($row1 = $stmt1->fetch()){
?>
<input type="file" name="image<?php echo ++$i ?>" value="<?php echo base64_encode($row1['picture']) ?>"/>
<?php
}
}
}
unset($stmt1);
}
} catch (Exception $e) {
var_dump($e->getMessage());
var_dump($e->getCode());
}
?>
<input type="submit" value="Next" />
</form>
</main>
</body>
</html>
Related
I´ve been working on this project for a quite while and, the other day I was doing some code when I walk by this piece of code that keeps giving me headaches. So i got my html and php code all right but whenever i try to upload an image to my database, the image goes null, what am i doing wrong?
<?php include "connection.php"; ?>
<?php
$n=$_POST["num"];
$t=$_POST["texto"];
$i=$_POST["imagem"];
$img = mysql_query("SELECT imagem2 from segurancaofensiva where nmr=$n");
$file = $_FILES['imagem']['tmp_name'];
$image = addslashes(file_get_contents($file));
$count = $connect->query("SELECT COUNT(DISTINCT nmr) FROM segurancaofensiva")->fetch_row()[0];
if ($connect->connect_error){
die("Connection failed: " . $connect->connect_error);
}
$sql = "UPDATE segurancaofensiva SET texto='$t', imagem='{$image}', imagem2='{$image}' where nmr=$n" ;
$sql1 = "UPDATE segurancaofensiva SET texto='$t', imagem='$img' where nmr=$n";
if ($_FILES['imagem']['name']!=='' && $connect->query($sql) !== false )
{
if ($n <= $count) {
echo "actualizou\n\n";
var_dump($n);
var_dump($i);
var_dump($image);
}
else
{
echo "nao atualizou numero fora dos limites";
}
} else {
if ($connect->query($sql1) !== false){
echo "atualizou\n\n";
} else {
echo "errp";
}
}
$connect->close();
?>
<?php include 'connection.php'; ?>
<?php
$campo = $_POST['selected'];
$query = "SELECT campo FROM segurancaofensiva";
$result1 = mysqli_query($connect, $query);
$stored = $campo;
$obterquery = "SELECT * FROM segurancaofensiva where campo ='$campo'";
$x = $connect->query ($obterquery) or die ("Erro na variavel resultado");
$final = $x->fetch_array (MYSQL_ASSOC);
?>
<html>
<body>
<head>
<link rel="stylesheet" type="text/css" href="css/styleBO.css">
</head>
<div class="formulario" style="width: 100%; height: 100%;">
<form name="form2" method="POST" action="">
<h6>Campo:</h6> <select name ="selected" id="selected" >
<?php while($row1 = mysqli_fetch_array($result1)):;?>
<option value="<?php echo $row1[0];?>"><?php echo $row1[0];?></option>
<?php endwhile;?>
</select>
<input type="submit" id="load" class="load" name="load" value="Carregar">
<input type="hidden" name="selectedValue" value="0"/><br>
</form>
</div>
<div class="formulario" id="form2" style="width: 100%; height: 100%;">
<form name="form1" target="apresenta" method="POST" action="menu3.php">
<label> Atualizar dados </label><br>
<h6>Texto:</h6><textarea name="texto" id="texto"><?php echo htmlspecialchars($final['texto']);?></textarea><br>
<h6>Imagem:</h6><input type="file" name="imagem"><br>
<input type="hidden" value="<?php echo htmlspecialchars($final['nmr']);?>" name="num">
<input type="submit" name="submit" value="Enviar" class="topo">
<input type="reset" value="Limpar" class="topo">
</form>
</div>
</body>
</html>
Change form html like below. PHP will not detect file object without this.
<form enctype="multipart/form-data">
Add form attribute as per your requirement.
You are missing enctype attribute in form tag
enctype='multipart/form-data'
If you post data and trying to upload file you must use enctype
EDITED: Answered by #James solution is bolded in the code below.
Thanks again #James.
I have a form(HTML) which has a text field and upload a file to database.
Before I was using
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST" name="form1" enctype="multipart/form-data"></pre>
It was working fine, now I want the page to submit the entries to database and display a different page so I tried this
<form action="page3.php"......>, but didn't worked.
However when I click Submit button it make the entry for text field in database but does not upload the file to database.
What I want it to do is: when I click submit button, text field gets entered in database, file gets uploaded to database folder(and my program make its path entry to database), and new page which is loaded for the user to see.
Any help is appreciated. Thanks.
my php code
<?php
//ob_start();
$host="localhost";
$username="root";
$password="";
$db_name="newrep";
$table_name="members";
$conn=new mysqli('localhost','root','','newrep');
if(!$conn){
die("cannot connect.");
}
//else if(!mysql_select_db($db_name)){
// die(" cannot select database.");
//}
session_start();
use foundationphp\UploadFile;
echo "Session value: ".$_SESSION['texas'];
$currentuser=$_SESSION['texas'];
echo $currentuser;
$current_year=date("Y");
//code for upload starts here
require_once 'src/foundationphp/UploadFile.php';
if (!isset($_SESSION['maxfiles'])) {
$_SESSION['maxfiles'] = ini_get('max_file_uploads');
$_SESSION['postmax'] = UploadFile::convertToBytes(ini_get('post_max_size'));
$_SESSION['displaymax'] = UploadFile::convertFromBytes($_SESSION['postmax']);
}
$max = 2048 * 1024;
$result = array();
//upload code ended above
if(!isset($_SESSION['texas']))
{
header('Location:login_page.php');
exit();
}
else {
if(isset($_POST['title'])){
echo "reaching the else";
if(isset($_POST['upload'])){
//upload in POST is for upload
print_r($_FILES);
$destination = __DIR__ . '/uploaded/'; //for upload
//upload code try and catch
try {
$upload = new UploadFile($destination);
$upload->setMaxSize($max);
//$upload->allowAllTypes();
$upload->upload();
$result = $upload->getMessages();
}
catch (Exception $e) {
$result[] = $e->getMessage();
}
}
$error = error_get_last();
if ($result || $error){
//<ul class="result">
if ($error){
echo "{$error['message']}"; }
if ($result) {
foreach ($result as $message) {
echo "<li>$message</li>";}}}
$file_path_variable= $destination.$_SESSION['current_filename'];
echo $file_path_variable;
$title=$_POST['title'];
$query="INSERT INTO proposal(title_prop, userName_prop,whitepaper_prop,year_prop) VALUES('$title','$currentuser','$file_path_variable','$current_year')";
$result_query=mysqli_query($conn,$query);
echo " in elseif ";
if(!$result_query){
echo " cannot insert ";
}
else {
**header('Location: page3.php');
exit();**
//echo "successful entry ";
}
}
//ob_end_flush();
?>
HTML code here:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Online Application</title>
<!-- <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> -->
<link href="bootstrap.min.css" rel="stylesheet">
<head><script src="bootstrap.min.js"></script> </head>
<body>
<div id="O_o"><br><h4>Texas State University</h4></div>
<div id="wrapper">
<form action=**"<?php $_SERVER['PHP_SELF']?>"** method="POST" id="whitepaper" name="whitepaper" role="form" enctype="multipart/form-data">
<legend><h5><b>Online Application</b></h5></legend>
<h4 id="reference" name="reference" class="heading-reference"><b>Proposal Whitepaper</b></h4>
<fieldset>
<center>
<div class="form-group">
<?php echo "Year of Proposal: $current_year";?><br>
<label class="label_title control-label" for="title">Submit Title of your proposal:</label>
<input id="title" name="title" type="text" placeholder="" class="input_title form-control" >
<p class="help-block">All fields are required.</p><!--
<button type="submit" id="submit_button" name="btn-primary" class="btn btn-primary"> Submit Title </button>-->
</div>
<div class="form-group">
<label class="label_whitepaper control-label" for="file">Upload the whitepaper of your proposal here: <br>Only .docx , .doc and .pdf format extensions are permitted.</label>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max;?>">
<p><input type="file" id="filename" name="filename[]" title="Browse for whitepaper" class="btn-primary" multiple
data-maxfiles="<?php echo $_SESSION['maxfiles'];?>"
data-postmax="<?php echo $_SESSION['postmax'];?>"
data-displaymax="<?php echo $_SESSION['displaymax'];?>"></p>
File should be no more than <?php echo UploadFile::convertFromBytes($max);?>.<br>
<!--<p><input type="submit" name="upload" value="Upload File" class="btn-primary">-->
<button id="submit" name="upload" class="btn-primary" >Submit and continue</button>
</div>
</center>
</fieldset>
</form>
</div>
<script src="js/checkmultiple.js"></script>
<script src="jquery.min.js"></script>
<script src="prettify.js"></script>
<script src="bootstrap.file-input.js"></script>
<script>
$(document).ready(function(){
$('input[type=file]').bootstrapFileInput();
});
</script>
</body>
</html>
<?php }
mysqli_close($conn);
?>
You need to include enctype='multipart/form-data' in your form tag:
<form action='<?php echo $_SERVER['PHP_SELF']?>' method="POST" name="form1" enctype='multipart/form-data'>
Without it, attachments cannot be sent through the form.
Update
Try the below code. I fixed some HTML errors as well.
<?php
//ob_start();
$host="localhost";
$username="root";
$password="";
$db_name="newrep";
$table_name="members";
$conn=new mysqli('localhost','root','','newrep');
if(!$conn){
die("cannot connect.");
}
//else if(!mysql_select_db($db_name)){
// die(" cannot select database.");
//}
session_start();
use foundationphp\UploadFile;
echo "Session value: ".$_SESSION['texas'];
$currentuser=$_SESSION['texas'];
echo $currentuser;
$current_year=date("Y");
//code for upload starts here
require_once 'src/foundationphp/UploadFile.php';
if (!isset($_SESSION['maxfiles'])) {
$_SESSION['maxfiles'] = ini_get('max_file_uploads');
$_SESSION['postmax'] = UploadFile::convertToBytes(ini_get('post_max_size'));
$_SESSION['displaymax'] = UploadFile::convertFromBytes($_SESSION['postmax']);
}
$max = 2048 * 1024;
$result = array();
//upload code ended above
if(!isset($_SESSION['texas']))
{
header('Location:login_page.php');
exit();
}else {
if(isset($_POST['title'])){
echo "reaching the else";
if(isset($_POST['upload'])){
//upload in POST is for upload
print_r($_FILES['fieldname']);
$destination = __DIR__ . '/uploaded/'; //for upload
//upload code try and catch
try {
$upload = new UploadFile($destination);
$upload->setMaxSize($max);
//$upload->allowAllTypes();
$upload->upload();
$result = $upload->getMessages();
}catch (Exception $e) {
$result[] = $e->getMessage();
}
}
$error = error_get_last();
if ($result || $error){
//<ul class="result">
if ($error){
echo "{$error['message']}"; }
if ($result) {
foreach ($result as $message) {
echo "<li>$message</li>";
}
}
}
$file_path_variable= $destination.$_SESSION['current_filename'];
//echo $file_path_variable;
$title=$_POST['title'];
$query="INSERT INTO proposal(title_prop, userName_prop,whitepaper_prop,year_prop) VALUES('$title','$currentuser','$file_path_variable','$current_year')";
$result_query=mysqli_query($conn,$query);
//echo " in elseif ";
if(!$result_query){
echo " cannot insert ";
}else {
header('Location: page3.php');
exit();
//echo "successful entry ";
}
}
//ob_end_flush();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Online Application</title>
<!-- <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> -->
<link href="bootstrap.min.css" rel="stylesheet">
<script src="bootstrap.min.js"></script>
</head>
<body>
<div id="O_o"><br><h4>Texas State University</h4></div>
<div id="wrapper">
<form action="<?php= $_SERVER['PHP_SELF']?>" method="POST" id="whitepaper" name="whitepaper" role="form" enctype="multipart/form-data">
<fieldset>
<legend><h5><b>Online Application</b></h5></legend>
<h4 id="reference" name="reference" class="heading-reference"><b>Proposal Whitepaper</b></h4>
<center>
<div class="form-group">
<?php echo "Year of Proposal: $current_year";?><br>
<label class="label_title control-label" for="title">Submit Title of your proposal:</label>
<input id="title" name="title" type="text" placeholder="" class="input_title form-control" >
<p class="help-block">All fields are required.</p><!--
<button type="submit" id="submit_button" name="btn-primary" class="btn btn-primary"> Submit Title </button>-->
</div>
<div class="form-group">
<label class="label_whitepaper control-label" for="file">Upload the whitepaper of your proposal here: <br>Only .docx , .doc and .pdf format extensions are permitted.</label>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max;?>">
<p><input type="file" id="filename" name="filename[]" title="Browse for whitepaper" class="btn-primary" multiple
data-maxfiles="<?php echo $_SESSION['maxfiles'];?>"
data-postmax="<?php echo $_SESSION['postmax'];?>"
data-displaymax="<?php echo $_SESSION['displaymax'];?>"></p>
File should be no more than <?php echo UploadFile::convertFromBytes($max);?>.<br>
<!--<p><input type="submit" name="upload" value="Upload File" class="btn-primary">-->
<button id="submit" name="upload" class="btn-primary" >Submit and continue</button>
</div>
</center>
</fieldset>
</form>
</div>
<script src="js/checkmultiple.js"></script>
<script src="jquery.min.js"></script>
<script src="prettify.js"></script>
<script src="bootstrap.file-input.js"></script>
<script>
$(document).ready(function(){
$('input[type=file]').bootstrapFileInput();
});
</script>
</body>
</html>
<? }
mysqli_close($conn);
?>
I am writing an app to delete and modify files in a directory. I deleted files successfully. And now I want to modify and update content to the same file using textarea on another page.
<form enctype="multipart/form-data" method="post">
<div class="span7">
<table>
<thead>
<tr>
<th> List of files </th>
<tr>
</thead>
<?php
$files = glob("UploadFile/"."*");
foreach($files as $txt)
{
if(mime_content_type($txt)=="text/plain")
{
$txtname = basename($txt);
echo "<tr><td><input type='radio' name='txt' value='$txtname'/> ".$txtname."</td></tr>";
}
}
?>
</table>
</div>
<div class="span8">
<button type="submit" name="submit" value="Edit">Edit</button>
<button type="submit" name="submit" value="Delete">Delete</button>
</div>
<?php
global $txtname;
$val = $_POST["submit"];
$txtname = $_POST["txt"];
if($val=="Delete")
unlink("UploadFile/".$txtname);
else if($val=="Edit")
{
$content=file_get_contents("UploadFile/".$txtname);
header('Location:/edit.php');
/* send content to this 'edit.php' page */
}
?>
</form>
And the edit.php page, i simply checked if the code is working. It works fine.
<?php
if($_POST['append'])
{
$file_open = fopen("UploadFile/file.txt","a+");
fwrite($file_open, $_POST['append']);
fclose($file_open);
}
?>
<form enctype="multipart/form-data" action="<?=$PHP_SELF?>" method="post">
<textarea name="append" value="">
<?php
echo $content;
$datalines = file ("UploadFile/file.txt");
foreach ($datalines as $zz)
{
echo $zz;
}
?>
</textarea>
<button type="submit" name="submit" value="save"> Save </button>
How do I get the contents of the file to textarea for modifying it.Update: I want to save changes to the same file. Thank you
<?php
if(isset($_POST['text']))
{
file_put_contents("file.txt",$_POST['text']);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
$text = file_get_contents("file.txt");
?>
<form method="post">
<textarea name="text"><?=$text?></textarea>
<input type="submit">
</form>
with listing
if(isset($_POST['text']))
{
file_put_contents("UploadFile/".basename($_POST['file']),$_POST['text']);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
if(isset($_GET['file']))
{
$text = file_get_contents("UploadFile/".basename($_GET['file']));
?>
<form method="post">
<input type="hidden" name="file" value="<?=urlencode($_GET['file'])?>">
<textarea name="text"><?=$text?></textarea>
<input type="submit">
</form>
<?
} else {
$files = glob("UploadFile/*");
foreach ($files as $f)
{
$f=basename($f);
?><?=htmlspecialchars($f)?><br><?
}
}
I am trying to update a record in a database. The code is meant to allow users to update an entry on a website with the option to edit the image as well. When I was initially testing this code it worked with no issues. When they selected an image it would update the image, and when they did not select an image it would not include the image in the updating. When I moved this code to the page that it needs to be on it is no longer working. It is always reading it as if the user has not selected an image to upload. The only thing that has changed between the test code and this code is the names in the database, and the addition of mysql_real_escape_string() for the variables $title and $description.
Here is the PHP code that is not working for me:
<?php
require_once ("connect.php");
if (isset($_POST['description'])) {
$id = $_GET['id'];
$title = $_POST['title'];
$description = $_POST['description'];
$title = mysql_real_escape_string($title);
$description = mysql_real_escape_string($description);
$target = "../images/contests/";
$target = $target.basename( $_FILES['image']['name']);
$ok=1;
if($_FILES['image']['name'] == "") {
$query = "UPDATE tbl_contests SET contests_title='$title', contests_description='$description' WHERE contests_id='$id'";
$result = mysql_query ($query);
if ($result) {
header ("Location: contests.php?=noimage");
exit ();
} else {
header ("Location: contests.php?=error");
exit ();
}
} else {
if ($ok==0){
header("Location: contests.php?=error");
} else {
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){
echo "<p>Your upload was sucessful.</p>";
$query = "UPDATE tbl_contests SET contests_title='$title', contests_description='$description', contests_image='$target' WHERE contests_id='$id'";
$result = mysql_query ($query);
if ($result) {
header ("Location: contests.php?=image");
exit ();
} else {
header ("Location: contests.php?=error");
exit ();
}
}
}
}
}
?>
Here is the form pertaining to the above code:
<?php
$postnum = $_GET['id'];
$query = "SELECT * FROM tbl_contests WHERE contests_id=".$postnum;
$result= mysql_query($query);
$row = mysql_fetch_array($result);
$path = "../images/contests/";
?>
<form action="update-past.php?id=<?php print $row[contests_id]; ?>" method="post" id="updatepast">
<br /><label>Title:</label> <p><input type="text" name="title" id="title" class="input" value="<?php print $row[contests_title]; ?>" /></p>
<?php if ($row['contests_image'] == !null) { ?>
<p><img src="<?php print $path.$row['contests_image']; ?>" width="425" height="500" /></p>
<br /><label>Edit Image: (Optional)</label> <p><input name="image" type="file" id="image" class="file" size="50" /></p>
<?php } else { ?>
<br /><br /><br /><br /><label>Add Image: (Optional)</label> <p><input name="image" type="file" id="image" class="file" size="50" /></p>
<?php } ?>
<br /><br /><br /><br /><br /><label>Description:</label><p><textarea name="description" cols="85" id="description" class="contentinput" rows="10"><?php print $row[contests_description]; ?></textarea></p>
<p><input type="submit" name="submit" id="button" value="Edit" /></p>
</form>
Try adding this to the form: enctype="multipart/form-data"
Here's some reading on form content types: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
In following code, how can I add a button or a link that sorts the data by 'name'?
The following code is just an example, a modified version of code that I found from http://fwebde.com/php/sqlite-php/ . The structure of the code is so enjoyable that I would like to improve it with a sorting-element.
Thanks!
<?php
$db = new PDO('sqlite:db.db');
if (isset($_POST['name']) && isset($_POST['message'])) {
try {
$stmt = $db->prepare("INSERT INTO messages (name, message) VALUES (:name, :message);");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':message', $message);
$title = $_POST['name'];
$content = $_POST['message'];
$stmt->execute();
} catch (Exception $e) {
die ($e);
}
}try {
$posts = $db->prepare('SELECT * FROM messages;');
$posts->execute();
} catch (Exception $e) {
die ($e);
}
?>
<?php while ($post = $messages->fetchObject()): ?>
<?php echo $post->name ?>
<?php echo $post->message ?>
<?php endwhile; ?>
<form action="" method="post">
<label for="name">Name:</label>
<input type="text" name="name" />
<textarea name="message" rows="8" cols="50"></textarea>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
$db = new PDO('sqlite:db.db');
if (isset($_POST['submit']) && isset($_POST['name']) && isset($_POST['message'])) {
try {
//Insert data
} catch (Exception $e) {
die ($e);
}
}
try {
$order = "";
if(isset($_POST['sort'])){
$order = " ORDER BY `name`"; // Order list by name
$orderFlag = 1;
if(isset($_POST['order']) && $_POST['order'] == 1){
$order .= " DESC";
$orderFlag = 0;
}
}
$posts = $db->prepare("SELECT * FROM `messages`" . $order . ";");
$posts->execute();
} catch (Exception $e) {
die ($e);
}
?>
<?php while ($post = $posts ->fetchObject()): ?>
<?php echo $post->name ?><?php echo $post->message ?><br/>
<?php endwhile; ?>
<form action="" method="post">
<!--pushing this button sort by name -->
<input type="submit" name="sort" value="Sort by name" />
<input type="hidden" name="order" value="<?=$orderFlag?>" />
<label for="name">Name:</label>
<input type="text" name="name" />
<textarea name="message" rows="8" cols="50"></textarea>
<!--pushing this button insert new data -->
<input type="submit" name="submit" value="Submit" />
</form>