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
Related
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>
so today I was trying to upload photo from admin file to user file. One thing I discovered is that my code works fine, but something is a little bit wrong I don't know where. When I successfully uploaded the picture, the picture didn't appear. But it successfully been uploaded. Could you help me out?
This is the code I used to upload the picture
<?php
require_once ('db/database.php');
if(isset($_POST['submit']))
{
$name = basename($_FILES['file_upload']['name']);
$t_name = $_FILES['file_upload']['tmp_name'];
$dir = 'fotovid';
$kat = $_POST['kat'];
if(move_uploaded_file($t_name, $dir."/".$name))
{
mysqli_select_db($koneksi, 'koneksi_oop');
$query = "INSERT INTO gallery (id_gambar, kat_gambar, nama_gambar, path) VALUES ('', $kat, '$name', 'fotovid/$name')";
$res = mysqli_query($koneksi, $query);
echo "Berhasil upload foto";
} else {
echo "Gagal upload foto";
}
}
?>
<div class="wrapper">
<div class="panel"">
<div align="center" style="padding-top: 100px;">
<!-- <div class="container1" style="background-color: none;margin-bottom: 235px;">
<label for="file-input">Upload Video</label>
<input type="file" accept=".mp4,.mkv" id = "file-input" style="background-color: none; width: 300px; "><br/>
<script type="text/javascript" src = "assets/js/videoJS.js"></script>
</div> -->
<form action="inputfoto.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_upload" /><br/>
<label>Kategori</label>
<input type="text" name="kat"><br/>
<input type="submit" name="submit" value="Upload">
</form>
</div>
</div>
</div>
While this is the class where I call 2 categories from database, which is 'Foto' and 'Video'.
<?php
include ('admin/db/database.php');
$query = "SELECT * FROM kategori_gambar";
$res = mysqli_query($koneksi, $query);
while ($row=mysqli_fetch_array($res))
{
?>
<div>
<fieldset style="margin:0px 40px 100px 40px;">
<legend>
<a href="keluar_gambar.php?kat_gambar=<?= $row['id'];?>">
<?php
echo $row['nama'];
?>
</a>
</legend>
</fieldset>
</div>
<?php
}
?>
And the last one is where the output should comes out.
$query = "SELECT * FROM gallery WHERE kat_gambar =".$_GET['kat_gambar'];
$res = mysqli_query($koneksi, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
while($row=mysqli_fetch_array($res))
{
?>
<img src = "<?php echo $row['path']; ?>" width='300px' height= "200px" /><br/>
<?php
}
?>
This is what happened when I tried to insert the image
enter image description here
enter image description here
enter image description here
enter image description here
I think there is a permission issue. could you please show us the output of the following code.
$row=mysqli_fetch_array($res)
and also check the folder where you tried to upload.
I'm having difficulties to insert the value as blob type always empty and the other method can't insert the images in a folder. Please you can show the way out. Thanks! This code is to save the image in a folder and then access it with the name to display, but is not saving the photos to the folder. I edited and include the form here, containing JavaScript and css .It looks some how messy but i'm a beginner. Thanks.
<?php
include("../views/post_form.php");
require("../includes/include.php");
require("../includes/sess_n.php");
if ($_SERVER["REQUEST_METHOD"]== "POST")
{
$usertext = $_POST["usertext"];
$image = $_FILES['image']['name'];
$talent =$_POST["talenttype"];
if(empty($usertext) || empty($image)|| empty($talent))
{
die();
}
$id = $_SESSION["id"];
$folder ="images/".basename($_FILES['image']['name']);
move_uploaded_file($_FILES['image']['tmp_name'],$folder) ;
$query = mysqli_query($link,"SELECT * FROM `upload` WHERE id = '$id'");
$upload = mysqli_query($link,"INSERT INTO `upload` (description,image,talent,folder) VALUES('$usertext','$image','$talent','$folder ')");
}
?>
To display, I want the photos to be save to the folder, not saving. I used blob method not inserting into the database.
<?php
include("../views/feeds_form.php");
require("../includes/include.php");
require("../includes/sess_n.php");
$query = mysqli_query($link,"SELECT * FROM `upload` ");
if ($query === false)
{
die();
}
echo '<table>';
while ($run = mysqli_fetch_assoc($query))
{
echo '<tr>';
echo '<td>';?> <img src =" <?php echo $run["image"]; ?>" height=100 width=100> <?php echo '<td>';
echo '<td>'; echo $run["description"]; echo '<td>'; echo $run["folder"];echo '<td>';
echo '</tr>';
}
echo '</table>';
?>
The form here.
<?php
include("../public/header.php");
?>
<div><title>post</title></div>
<style>
.form-inline
{
text-align: center;
margin-bottom: 50px;
}
</style>
<script type="text/javascript">
function validate(){
var usertext = document.getElementById("usertext");
var talent = document.getElementById("talenttype");
var image = document.getElementById("image");
if (usertext.value === "" && talent.value === "" && image.value ==="")
{
alert("Field Must Not be Empty");
}
}
</script>
<form class="form-inline" method ="POST" action ="post.php" enctype="multipart/form-data" onsubmit= "return validate();">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3"> </label>
<textarea class="form-control" id = "usertext" name ="usertext" rows="5" placeholder="Describe Person Here"></textarea> <br><hr>
<label class="sr-only" for="exampleInputEmail3"></label><br>
<div class="form-group">
<label for="exampleInputPassword1"></label>
<input type="file" class="form-control" id = "image" id="exampleInputPassword1" name="image" placeholder="image">
</div> <br><br><br> <hr>
<div class="form-group">
<label for="exampleInputPassword1"></label>
<input type="text" class="form-control" id = "talenttype" id="exampleInputPassword1" name = "talenttype" placeholder="Talent-Type"><br><br>
</div> <hr>
<div>
<button type="submit" name ="post" class="btn btn-default">Post</button><br>
</div>
</div>
</form>
<?php
include("../public/footer.php");
?>
I was having permission issues, the images folder permission was changed. That solves everything. Thanks!
I have following code:
<html>
<head>
<meta charset="UTF-8"/>
</head>
<body>
<!--See siin all tekstiväli-->
<H3>Minu küsitlused </H3>
<hr>
<br>
<br>
<br>
<ol>
<?php
include_once 'init/init.funcs.php';
$result = mysql_query('SELECT * from katse_kysimustik_pealkiri');
while($row = mysql_fetch_assoc($result)) {
$titles[] = $row['pealkiri'];
}
foreach($titles as $title) {?>
<li>
<?php echo $title ?>
<form action='Minu_kysitlused_1.php' method="post">
<input type="submit" name = "saada" value="saada"/>
<input type="button" value="tulemused"/>
<input type="button" value="lõpeta ennetähtaegselt"/>
<input type="button" value="X"/>
</li>
</form>
<?php
}
?>
</ol>
</body>
</html>
<?php
if(isset($_POST['saada'])){
header("Location:http://localhost/Praks/saada.html");
}
?>
Right now there is button "saada" for each title in database. When I click "saada", page saada.html will appear.
This is saada.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Saada</title>
</head>
<form action="test1.php" method="POST">
<body>
<header>Küsitluse pealkiri</header>
<br>
Lisa sõnumile pealkiri:
<br>
<textarea rows='1' name='pealkiri'>Küsitluse algne pealkiri</textarea>
<br>
Lisa Adressaadid: <br>
<textarea rows='1' name='email'></textarea>
<br>
Lisa sõnum:
<br>
<textarea rows='4' name='tekst'></textarea>
<br><footer>
<INPUT TYPE="submit" VALUE="Saada" NAME="Saada">
</form>
<FORM METHOD="LINK" ACTION="Minu_kysitlused.html">
<INPUT TYPE="submit" VALUE="Loobu">
</footer>
</body>
</html>
My question is how could I make it work so value of $title appears in saada.html. The value of this $title which is next to 'saada' button I clicked. I need this value to be in this line instead of Küsitluse algne pealkiri:
<textarea rows='1' name='pealkiri'>Küsitluse algne pealkiri</textarea>
You can not have a value through PHP in HTML type page....change page extension to .php
then pass your $title in input hidden field in your form
like this
foreach($titles as $title) {?>
<li>
<?php echo $title ?>
<form action='Minu_kysitlused_1.php' method="post">
<input type="submit" name = "saada" value="saada"/>
<input type="button" value="tulemused"/>
<input type="button" value="lõpeta ennetähtaegselt"/>
<input type="button" value="X"/>
<input type="hidden" name="title" value="<?php echo $title;?>"/>
</li>
</form>
<?php
}
?>
Now set the cookie
<?php
if(isset($_POST['saada']))
{
if(isset($_REQUEST['title']))
{
$title = $_REQUEST['title'];
setcookie("page_title", $title, time()+3600);
}
header("Location:http://localhost/Praks/saada.html");
}
?>
Now on Your saada.html you can use js to retrieve cookie like this
JS Function Reference
var title = getCookie("page_title"); // retrieve cookie
document.getElementById('page_title').value = title; // put title into textaread
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
<textarea rows='1' name='pealkiri' id="page_title" >Küsitluse algne pealkiri</textarea>
Currently I have a form that makes use of fields and check boxes. The fields and checkboxes both update the database perfectly:
<?php
function renderForm($articletitle, $articleorganization, $articledate, $articleurl, $articletags )
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="stylized" class="myform">
<form id="form" name="form" action="" method="post">
. . .
. . .
if(count($articletags) > 0)
{
$articletags_string = implode(",", $articletags);
}
if (isset($_POST['submit']))
{
$articletitle = mysql_real_escape_string(htmlspecialchars($_POST['articletitle']));
$articleorganization = mysql_real_escape_string(htmlspecialchars($_POST['articleorganization']));
$articledate = mysql_real_escape_string(htmlspecialchars($_POST['articledate']));
$articleurl = mysql_real_escape_string(htmlspecialchars($_POST['articleurl']));
$articletags = implode(',', $_POST['articletags']);
. . .
mysql_query("INSERT articles SET articletitle='$articletitle', articleorganization='$articleorganization', articledate='$articledate', articleurl='$articleurl', articletags='$articletags' ")
or die(mysql_error());
// once saved, redirect to success page
header("Location:addsuccess.html");
}
}
else
{
renderForm('','','','');
}
?>
Now, though, I'm wondering if I should have gone with a boolean checkbox instead.
The reason is that I've built an edit form as well and it follows the new entry form exactly except that values are already filled in via the MySQL DB.
So, I'm assuming that it would be considerably easier to use boolean, right?
So, instead of using an array, I should give the checkboxes different names, and on the edit.php page I can use something like:
<?php
function renderForm($id, $articletitle, $articleorganization, $articledate, $articleurl, $articletags)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="stylized" class="myform">
<form id="form" name="form" action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<h1>Edit Details for <?php echo $articletitle; ?></h1>
<fieldset>
<legend>Article details</legend>
<div class="row">
<div class="field"><label>Article Title</label><input type="text" name="articletitle" value="<?php echo $articletitle; ?>"/></div>
</div>
<div class="row">
<div class="field"><label>Article Author </label><input type="text" name="articleorganization" value="<?php echo $articleorganization; ?>"/></div>
<div class="field"><label>Article Date </label><input type="text" name="articledate" value="<?php echo $articledate; ?>"/></div>
</div>
<div class="row">
<div class="field"><label>Article Url: </label><input type="text" name="articleurl" value="<?php echo $articleurl; ?>"/></div>
<div class="row">
<input type="checkbox" name="articletags1" value="checkbox" id="articletags_0" />
<input type="checkbox" name="articletags2" value="checkbox 2" id="articletags_1" />
</div>
</fieldset>
<footer><input type="submit" name="submit" value="Submit"></footer></form>
</div>
</body>
</html>
<?php
}
include('settings.php');
if (isset($_POST['submit']))
{
if (is_numeric($_POST['id']))
{
$id = $_POST['id'];
$articletitle = mysql_real_escape_string(htmlspecialchars($_POST['articletitle']));
$articleorganization = mysql_real_escape_string(htmlspecialchars($_POST['articleorganization']));
$articledate = mysql_real_escape_string(htmlspecialchars($_POST['articledate']));
$articleurl = mysql_real_escape_string(htmlspecialchars($_POST['articleurl']));
$articletags = implode(',', $_POST['articletags']);
if ($articletitle == '' || $articletags == '')
{
$error = 'ERROR: Please fill in all required fields!';
renderForm($id, $articletitle, $articletags);
}
else
{
mysql_query("UPDATE articles SET articletitle='$articletitle', articleorganization='$articleorganization', articledate='$articledate', articleurl='$articleurl', articletags='$articletags' WHERE id=$id")
or die(mysql_error());
header("Location: editsuccess.html");
}
}
else
{
echo 'Error!';
}
}
else
{
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM articles WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
$articletitle = $row['articletitle'];
$articleorganization = $row['articleorganization'];
$articledate = $row['articledate'];
$articleurl = $row['articleurl'];
$articletags = $row['articletags'];
renderForm($id, $articletitle, $articleorganization, $articledate, $articleurl, $articletags, '');
}
else
{
echo "No results!";
}
}
else
{
echo 'Error!';
}
}
?>
The problem with that though is that my checkboxes on the edit.php page still aren't showing the checked state.
You need to use checked="checked" in the same way as you used for value. See the solution bottom:
<input type="checkbox" <?php if(isset($_POST[articletags1])) echo 'checked="checked" ' ?>name="articletags1" value="checkbox" id="articletags_0" />
<input type="checkbox" <?php if(isset($_POST[articletags2])) echo 'checked="checked" ' ?>name="articletags2" value="checkbox 2" id="articletags_1" />
Hope this works. Updated the right code. Use ini_set('display_errors', 1); to get the error generated.