Notice: Undefined index: Image in C:\xampp\htdocs\site\AddNewPost.php on line 14


#1
<?php require_once("include/Db.php"); ?> <?php require_once("include/Sessions.php"); ?> <?php require_once("include/Functions.php"); ?> <?php if(isset($_POST['Submit'])){ $Title = mysqli_real_escape_string($conn, $_POST['Title']); $Category = mysqli_real_escape_string($conn, $_POST['Category']); $Post = mysqli_real_escape_string($conn, $_POST['Post']); date_default_timezone_set("Africa/Johannesburg"); $CurrentTime = time(); $DateTime=strftime("%B-%d-%Y %H:%M:%S", $CurrentTime); $DateTime; $Admin="Ismeal Muyanja"; $Image=$_FILES["Image"]["name"]; if(isset($_FILES["Image"])){ echo $_FILES["Image"]["name"]; $Target = "Upload/".basename($_FILES["Image"]["name"]); if(empty($Title)){ $_SESSION["ErrorMessage"] = "Title can't be empty"; Redirect_to("AddNewPost.php"); } elseif(strlen($Title)<2){ $_SESSION["ErrorMessage"] = "Title should be more than 2 characters"; Redirect_to("AddNewPost.php"); } else { global $conn; $sql ="INSERT INTO admin_panel(datetime, title, category, author, image, post) VALUES('$DateTime', '$Title', '$Category', $Admin, $Image, $Post)"; //$Execute= mysqli_query($sql); if($conn->query($sql) === True){ $_SESSION["SuccessMessage"] = "Post Added Succussfully"; Redirect_to("AddNewPost.php"); } else{ $_SESSION["ErrorMessage"] = "Post Failed To Add"; Redirect_to("AddNewPost.php"); } } } } ?> Add New Post .FieldInfo{ color: rgb(251, 174, 44); font-family: Bitter, Georgia,"Times New Roman", serif, Times; font-size: 1.2em; }

Add New Post

<?php echo Message(); echo SuccessMessage(); ?>

Title:

Category:

<?php global $conn; $sql = "SELECT * FROM categories ORDER BY datetime desc"; $result = $conn->query($sql); while($DataRows=$result->fetch_assoc()){ $Id=$DataRows["id"]; $CategoryName=$DataRows["name"]; ?> <?php echo $CategoryName; ?> <?php } ?>

Post:

Post:



#2

Hello hi.
Am looking for help. I have seen my code has smashed each other and un readable but my problem is undefined Image. This piece of code is the one on line 14: $Image=$_FILES[“Image”][“name”];

Am trying to upload image in database


#3

Well, when you post your code, you need to use the p preformatted tags. I sometimes use the preformatted tag and then the quoted tags, too. That puts the formatted code inside a quote block. Looks better that way.

Now, to upload a file here is an example of the code: https://www.w3schools.com/php/php_file_upload.asp
That will give you the basics. If you want us to review your code, please repost it so we can see it easier.
You should show us the file input line, too…


#4

There are a number of reason why an element in the $_FILES array might not exist -

  1. One of several possible problems with the html form - not a post method form, missing the enctype attribute, missing a type=‘file’ field, the form field isn’t inside the form, a misnaming between the form field and the php code, broken html markup, …
  2. Uploads are not enabled on the server.
  3. The total size of the submitted post data exceeds the post_max_size setting. In this case, both the $_POST and $_FILES arrays will be empty.
  4. The $_FILES array is being referenced without first detecting that a post method form was submitted.

The form processing code that handles a file upload needs to, in the order shown, and setting up helpful user error messages for each thing that can fail -

  1. Detect that a post method form has been submitted.
  2. Test for the condition in item #3 in the above list (you can also test for item #2 and report that uploads are not enabled.)
  3. Check for upload errors by testing the [‘error’] element in the $_FILES array. For errors the user can correct, setup a helpful error message telling the user exactly what he did wrong. For internal errors that the user cannot affect, output a generic failure message and log the actual error information.
  4. Validate the uploaded file information.
  5. Use the uploaded file information in the rest of the form processing code.

If your form processing code performs these steps, your code will either work or it will tell you why it isn’t working.

Since your current code is testing for the existence of a $_POST variable and all the form processing code is within that conditional block of code, this eliminates items #3 and #4 in the first list as possibilities.


#5

Thanks ErnieAlex for the reply.
I have tried to modify my code according to the link you gave me but clearly I’m missing out something. Please allow me to repost my code

<?php $target_dir = "Upload/"; $uploadImage = ""; $filename = $target_dir . basename($_FILES["uploadImage"]["name"]); $uploadOk = 1; if(isset($_POST['Submit'])){ $Title = mysqli_real_escape_string($conn, $_POST['Title']); $Category = mysqli_real_escape_string($conn, $_POST['Category']); $Post = mysqli_real_escape_string($conn, $_POST['Post']); date_default_timezone_set("Africa/Johannesburg"); $CurrentTime = time(); $DateTime=strftime("%B-%d-%Y %H:%M:%S", $CurrentTime); $DateTime; $Admin="Admin"; $check = getimagesize($_FILES["uploadImage"]["tmp_name"]); if($check !== false){ echo "File is an image - " . $check["name"] . $uploadOk = 1; $filetmpname = $_FILES["uploadImage"]; move_upload_file($_FILES["uploadImage"]["$filetmpname"], "Upload".$filename ); if(empty($Title)){ $_SESSION["ErrorMessage"] = "Title can't be empty"; Redirect_to("AddNewPost.php"); } elseif(strlen($Title)<2){ $_SESSION["ErrorMessage"] = "Title should be more than 2 characters"; Redirect_to("AddNewPost.php"); } else { global $conn; $sql ="INSERT INTO admin_panel(datetime, title, category, author, image, post) VALUES('$DateTime', '$Title', '$Category', '$Title', '$filename', '$Post')"; //$Execute= mysqli_query($sql); if($conn->query($sql) === True){ $_SESSION["SuccessMessage"] = "Post Added Succussfully"; Redirect_to("AddNewPost.php"); } else{ $_SESSION["ErrorMessage"] = "Post Failed To Add"; Redirect_to("AddNewPost.php"); } } } } ?>

.


#6

And this is the form.

Post:

#7

Well, Mah, first, I still can not read your code. It is all squashed up together. Let me explain how to post code like this. Since this code is already formatted by the editor that you are using, you must tell this site that it is preformatted. Also, if you want it in a nice scrollable format, you must also tell the site it is a quote. So, to post your code copy and past it here. Then, tag or highlight just the code. Once highlighted, press the < / > button and then press the Quote button. that will make it look like this:

<?PHP
$target_dir = "Upload/";
$uploadImage = "";
$filename = $target_dir . basename($_FILES["uploadImage"]["name"]);
$uploadOk = 1;
if(isset($_POST['Submit'])){
    $Title = mysqli_real_escape_string($conn, $_POST['Title']);
    $Category = mysqli_real_escape_string($conn, $_POST['Category']);
    $Post = mysqli_real_escape_string($conn, $_POST['Post']);
    date_default_timezone_set("Africa/Johannesburg");
    $CurrentTime = time();
    $DateTime=strftime("%B-%d-%Y %H:%M:%S", $CurrentTime);
    $DateTime;
    $Admin="Admin";
    $check = getimagesize($_FILES["uploadImage"]["tmp_name"]);
    if($check !== false){
    }
    echo "File is an image - " . $check["name"] . $uploadOk = 1;
    $filetmpname = $_FILES["uploadImage"];
    move_upload_file($_FILES["uploadImage"]["$filetmpname"], "Upload".$filename );
    if(empty($Title)){
    }
    $_SESSION["ErrorMessage"] = "Title can't be empty";
    Redirect_to("AddNewPost.php");
    } elseif(strlen($Title)<2) {
        $_SESSION["ErrorMessage"] = "Title should be more than 2 characters";
        Redirect_to("AddNewPost.php");
     } else {
     }
     global $conn;
     $sql ="INSERT INTO admin_panel(datetime, title, category, author, image, post) VALUES('$DateTime', '$Title', '$Category', '$Title', '$filename', '$Post')";
     //$Execute= mysqli_query($sql);
     if($conn->query($sql) === True) {
             $_SESSION["SuccessMessage"] = "Post Added Succussfully";
             Redirect_to("AddNewPost.php");
      } else{
              $_SESSION["ErrorMessage"] = "Post Failed To Add";
              Redirect_to("AddNewPost.php");
       }
   }
}

}
?>

This makes it easier for us to read! Now, looking at your code, it appears you do not understand how to use the “braces”, the { and } characters. When you use IF clauses, they are written something like this:

IF ( SOME-CONDITION ) {
      SOME-CODE;
      SOME-MORE-CODE;
      etc...
}

In some cases, you need to nest them inside of each other. In your code, you have some IF clauses that do nothing and then do not if ELSE clauses. If you look over the code, you should see a lot of errors in the way the flow of your code works. Also, since you did not use the preformatted button, your form did not show.
And, you mark the $conn variable as global AFTER you have already used it. I do not understand that one.
You show a redirect_to() function, but, I do not see that function listed. Normally, to move to another page,
you just use a “header()” function. I attempted to fix most of these and here is another version of it. I did not
have anyway to test it, but, it might work this way…

<?PHP
//  Not sure why you need this next line
global $conn;

//  Set up for file upload
$target_dir = "Upload/";
$uploadImage = "";
$filename = $target_dir . basename($_FILES["uploadImage"]["name"]);
$uploadOk = 1;

//  Check if the form was posted, if so, load the form's fields
if(isset($_POST['Submit'])){
    $Title = filter_input(INPUT_POST, 'Title');
    
    //  Validate title name before saving
    if(empty($Title)) {
        $_SESSION["ErrorMessage"] = "Title can't be empty";
        header("Location: AddNewPost.php");
    } elseif(strlen($Title)<2) {
        $_SESSION["ErrorMessage"] = "Title should be more than 2 characters";
        header("Location: AddNewPost.php");
    } else {
        //  Title is okay, now process the post
        $Category = filter_input(INPUT_POST, 'Category');
        $Post = filter_input(INPUT_POST, 'Post');
        date_default_timezone_set("Africa/Johannesburg");
        $CurrentTime = time();
        $DateTime = strftime("%B-%d-%Y %H:%M:%S", $CurrentTime);
        echo $DateTime;
        $Admin = "Admin";
        $check = getimagesize($_FILES["uploadImage"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["name"] . $uploadOk = 1;
            move_upload_file($_FILES["uploadImage"]["tmp_name"], "Upload/".$filename );
        
            //  File is uploaded, now enter into database
            $sql ="INSERT INTO admin_panel(datetime, title, category, author, image, post) VALUES('$DateTime', '$Title', '$Category', '$Title', '$filename', '$Post')";
            //$Execute= mysqli_query($sql);
            if($conn->query($sql) === True){
                $_SESSION["SuccessMessage"] = "Post Added Succussfully";
                header("Location: AddNewPost.php");
            } else {
                $_SESSION["ErrorMessage"] = "Post Failed To Add";
                header("Location: AddNewPost.php");
            }
        }
    }
}
?>

As you see, I changed the “mysqli_real_escape_string()” functions into the better “filter_input()” ones.
They are more secure and work better overall. I fixed the messed up braces and added some comments.
I am not sure this will work, but, it gives you a starting place. Test it and try to get it working and if not, let
us know and repost the latest version you have using the buttons to make it readable.

Good luck…


#8

Thanks ErnieAlex for the reply. Everything with is code is working besides the image doesn’t upload.
I tried to change as you did but still it gives error undifined Image

<?php require_once("include/Db.php"); ?>
<?php require_once("include/Sessions.php"); ?>
<?php require_once("include/Functions.php"); ?>
<?php
if(isset($_POST['Submit'])){
$Title = mysqli_real_escape_string($conn, $_POST['Title']);
$Category = mysqli_real_escape_string($conn, $_POST['Category']);
$Post = mysqli_real_escape_string($conn, $_POST['Post']);
date_default_timezone_set("Africa/Johannesburg");
$CurrentTime = time();
$DateTime=strftime("%B-%d-%Y %H:%M:%S", $CurrentTime);
$DateTime;
$Admin="Admin";
$Image=$_FILES["Image"]["name"];
$Target = "Upload/".basename($_FILES["Image"]["name"]);
if(empty($Title)){
$_SESSION["ErrorMessage"] = "Title can't be empty";
Redirect_to("AddNewPost.php");
} elseif(strlen($Title)<2){
$_SESSION["ErrorMessage"] = "Title should be more than 2 characters";
Redirect_to("AddNewPost.php");
} else {
global $conn;
$sql ="INSERT INTO admin_panel(datetime, title, category, author, image, post)
VALUES('$DateTime', '$Title', '$Category', '$Admin', '$Image', '$Post')";
//$Execute= mysqli_query($sql);
move_uploaded_file($_FILES["Image"]["tmp_name"],$Target );
if($conn->query($sql) === True){
$_SESSION["SuccessMessage"] = "Post Added Succussfully";
Redirect_to("AddNewPost.php");  
}
 else{
$_SESSION["ErrorMessage"] = "Post Failed To Add";
Redirect_to("AddNewPost.php");
}
}
}

?>
<!DOCTYPE HTML>
<html>
<head>
<title>Add New Post</title>
<link rel="stylesheet" href="css/bootstrap.min.css"/>
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<link rel="stylesheet" href="css/custom.css"/>

<style>
.FieldInfo{
color: rgb(251, 174, 44);
font-family: Bitter, Georgia,"Times New Roman", serif, Times;
font-size: 1.2em;
}</style>
</head>

<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-2">

<ul id="Side_Menu" class="nav nav-pills nav-stacked">
<li><a href="Dash.php">
<span class="glyphicon glyphicon-th"></span>&nbsp;Dashboard</a></li>
<li class="active"><a href="AddNewPost.php">
<span class="glyphicon glyphicon-list-alt"></span>&nbsp;Add New Post</a></li>
<li><a href="categories.php">
<span class="glyphicon glyphicon-tags"></span>&nbsp;Categories</a></li>
<li><a href="#">
<span class="glyphicon glyphicon-user"></span>&nbsp;Manage Admins</a></li>
<li><a href="#">
<span class="glyphicon glyphicon-comment"></span>&nbsp;Comments</a></li>
<li><a href="#">
<span class="glyphicon glyphicon-equalizer"></span>&nbsp;Live Blog</a></li>
<li><a href="#">
<span class="glyphicon glyphicon-log-out"></span>&nbsp;Logout</a></li>
</ul>
</div><!--Ending of side area-->
<div class="col-sm-10">
<h1>Add New Post</h1>
 <?php   echo Message();
        echo SuccessMessage();
?>
<div>
<form action="AddNewPost.php" method="post" enctype="multipart/form-data>
<fieldset>
<div class="form-group">
<label for="title"><span class="FieldInfo">Title:</span></label>
<input class="form-control" type="text" name="Title" id="Title" placeholder="Name"/>
</div>
<div class="form-group">
<label for="categoryselect"><span class="FieldInfo">Category:</span></label>
<select class="form-control" id="categoryselect" name="Category">
<?php
global $conn;
$sql = "SELECT * FROM categories ORDER BY datetime desc";
$result = $conn->query($sql);

while($DataRows=$result->fetch_assoc()){
$Id=$DataRows["id"];
$CategoryName=$DataRows["name"];           

?>  
<option><?php echo $CategoryName; ?> </option>
<?php } ?>

</select>
</div>
<div class="form-group">
<label for="imageselect"><span class="FieldInfo">Select Image:</span></label>
<input type="File" class="form-control" name="Image" id="imageselect"/>

</div>
<div class="form-group">
<label for="postarea"><span class="FieldInfo">Post:</span></label>
<textarea class="form-control" name="Post" id="postarea"></textarea>
</div>
<br />
<input class="btn btn-success btn-lg" type="Submit" name="Submit" value="Add New Post"/>
</fieldset>
</form>
</div>
<div class="table-responsive">



</div>
</div><!--Ending of Main area-->
</div><!--Ending of Row-->

</div><!--Ending of Container div-->
<div id="footer">
<p>Theme By | Php Learner | $copy;2018 ---All right reserved.</p>
<a style="color: white; text-decoration: none; 
cursor: pointer; font-weight: bold;"></a>

</div>



</body>
</html>

#9

did you get any errors posted? Do you know how to check for errors?
Add this at the very top of the page.

<?PHP
error_reporting(E_ALL);
ini_set("display_errors", 1);

This will turn on all error reporting. You would not do this on a live site, it is just for debugging your code.
Then, rerun your test page and see if it shows any errors.

If not, you will have to check your server logs. Where they are depends on what type of server you have.
In some shared servers, it will post errors in the same folder as the webpage. You would need to log into
your server and look in the folder where this page is stored. Then, look for an ERROR log of some sort.
Quite often it is a text file. Then, view that. Otherwise, it would be in your server’s logs folder. This can
be in many places on various types of servers. But, quite often is under the /var/ folder. The log folder
will be clearly marked like “logs” or similar. Then, in that folder there would be various types of logs like
FTP logs of who has logged into the FTP service and error logs. You would have to edit them and look
for the last entries to find any errors.

Add those two lines to the top. Rerun the page. Check for errors. If you do not see any, I will put this up
on my server and test it.

Also, can you show us the function “Redirect_to()” code? I do not see it. Maybe that code is breaking it.


#10

The enctype attribute in the form tag is missing a closing double-quote. In fact, this is also breaking the fieldset tag and you are not getting the expected box around the form fields.


#11

Good catch Phdr !

… Why does this stupid site force you to 20 characters per post! My 18 should have been enough! LOL


#12

I want to thank you all who help me solve this problem, finally I maneged to solve it.
In my query was missing

'".$DateTime."', '".$Title."', '".$Category."', '".$Admin."', '".$Image."', '".$Post."')