Link to home
Start Free TrialLog in
Avatar of sanchit gupta
sanchit gupta

asked on

Error executing Exception got executed only

I have created 4 input types name, price, description, brand and one input file type image. on being clicked on submit button i want all the 5 inputs to go into database table "product" but on submit being clicked it just displays the exception as output "Some of your fields are empty" but all fields are being filled. i can even provide the html code

 
<?php
    // Do we have a Form Submission
    if (isset($_POST['submit'])) {

        try {

            // Check that all your fields have values
            if (
                (!isset($_POST['name']) || empty($_POST['name'])) ||
                (!isset($_POST['desc']) || empty($_POST['desc'])) ||
                (!isset($_POST['price']) || empty($_POST['price'])) ||
                (!isset($_POST['brand']) || empty($_POST['brand'])) ||
                (!isset($_POST['image']) || empty($_POST['image']))
            ) {
                throw new Exception('Some of your fields are empty.');;
            }
                $filename = $_FILES['fileToUpload']['name'];
                $filetemp = $_FILES['fileToUpload']['temp_name'];
                $filesize = $_FILES['fileToUpload']['size'];
                $filebasename = basename($_FILES['fileToUpload']['name']);
                $dir="uploads/";
                $finaldir=$dir.$filebasename;
                move_uploaded_file($filetemp,$finaldir);

            // Prepare your Query and bind the parameters to the POST array
            $stmt = $db->prepare("INSERT INTO product (name, description, price, brand, image)  VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("ssss", $_POST['name'], $_POST['desc'], $_POST['price'], $_POST['brand'], $_POST['image']);

            // Execute your query
            $stmt->execute();

            // Success!
            printf("<p class='msg success'>%s</p>", "Your record was created.");

        } catch (Exception $e) {

            // There was a problem
            printf("<p class='msg error'>%s</p>", $e->getMessage());

        }
    }
    ?>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Anyway, never trust data from a form: always validate it. You can use filter_input() function. From your form bad guys could attempt to your site security.
You might even consider to learn about validation and sanitization.

A great resource about security is OWASP website
Avatar of sanchit gupta
sanchit gupta

ASKER

Well it removes that exception error thanks but few more errors arises i have removed some but one still remains there i.e.
Undefined index: temp_name
Column 'image' cannot be null

could you please help me out with these too.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Oh yes, At line 26 you have another $_POST['image'] that you must remove.
@Ray i being a beginner in backend did not understood that image upload snippet you provided.
Could you please help me in finding errors in my code so that i will have a better understanding of this logic.
@MarcoGasi I also want the image to be inserted in database removing that would not insert image database.
You have to use $_FILES['fileToUpload']['name']:
$stmt = $db->prepare("INSERT INTO product (name, description, price, brand, image)  VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("ssss", $_POST['name'], $_POST['desc'], $_POST['price'], $_POST['brand'], $_FILES['fileToUpload']['name']);

Open in new window


So full code would be:
<?php
    // Do we have a Form Submission
    if (isset($_POST['submit'])) {

        try {

            // Check that all your fields have values
            if (
                (!isset($_POST['name']) || empty($_POST['name'])) ||
                (!isset($_POST['desc']) || empty($_POST['desc'])) ||
                (!isset($_POST['price']) || empty($_POST['price'])) ||
                (!isset($_POST['brand']) || empty($_POST['brand'])) ||
                (!isset($_FILES['fileToUpload']['name']) || empty($_FILES['fileToUpload']['name']))
            ) {
                throw new Exception('Some of your fields are empty.');;
            }
                $filename = $_FILES['fileToUpload']['name'];
                $filetemp = $_FILES['fileToUpload']['temp_name'];
                $filesize = $_FILES['fileToUpload']['size'];
                $filebasename = basename($_FILES['fileToUpload']['name']);
                $dir="uploads/";
                $finaldir=$dir.$filebasename;
                move_uploaded_file($filetemp,$finaldir);

            // Prepare your Query and bind the parameters to the POST array
            $stmt = $db->prepare("INSERT INTO product (name, description, price, brand, image)  VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("ssss", $_POST['name'], $_POST['desc'], $_POST['price'], $_POST['brand'], $_FILES['fileToUpload']['name']);

            // Execute your query
            $stmt->execute();

            // Success!
            printf("<p class='msg success'>%s</p>", "Your record was created.");

        } catch (Exception $e) {

            // There was a problem
            printf("<p class='msg error'>%s</p>", $e->getMessage());

        }
    }
    ?>

Open in new window

@Marco undefined index temp_name still occurs
Sorry, I didn't see that: 'temp_name' doesn't exist. Use  $_FILES['fileToUpload']['tmp_name']
@Marco it worked upto all manner but just a single bug is that all the images are moving in uploads folder as it is. i want them to move them to a folder inside uploads folder.
Because you must create the folder befre you can use it: Php doesn't create it automatically.

   
$dir="uploads/";
$finaldir=$dir.$filebasename;
//IF DIRECTORY DOESN'T EXIST WE CREATE IT
if(!file_exists($finaldir)){
    mkdir($finaldir);
}
move_uploaded_file($filetemp,$finaldir);

Open in new window

You didn't get me i guess..
i have made a folder inside "uploads" folder named "newfiles"  and i want the insertion into that.
Just put it in $dir variable value
$dir="uploads/newfiles";

Open in new window

   
$dir="uploads/newfiles";
$finaldir=$dir.$filebasename;
move_uploaded_file($filetemp,$finaldir);

Open in new window

@Marco I already did that but it still comes in the uploads folder and not in the newfiles
If you are on a Unix-like environment, check foder permissions. Set permissions to 755.
I'm on windows..
Ok, I'm stupid: we need to add a trailing slash after newfiles otherwise the $finaldir is 'uploads/newfilesmyimage.jpg'!
$dir="uploads/newfiles/";
$finaldir=$dir.$filebasename;
move_uploaded_file($filetemp,$finaldir);

Open in new window

Instead of filter input would strip_tags help me out in same way?
help me out in applying filter input or strip tags too so that it will secure the database
Sanchit, I posted a link to filter_input man page and in addition filtering and sanitizing data is an totally different question. This is  basic example, but if you want go deeper you should close this question and open new one about this argument :)

$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
if (!empty($name){
...

Open in new window

In man pages you can find all required info to use it proficiently.
These comments solve the issue