Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to insert image to database

I have a problem inserting images in my database with a basic form. There is two forms, one inserts categories (an image and a name) and the other inserts a location(Name, Address, image, etc). The add_category function works fine it's the add_location that doesn't and specifically inserting the image. And I believe it's inserting the image that is problematic.

The problem is that this if statement in the insert image never get executed and I don't know why. It's in the function add_location(..) under the check image if statement.

if ($result = $this->mysqli->query($query)) {
    $error['result'] = $this->succAddLoc;
}

I removed unnecessary functions in the file:

<?php 
    class pongodev {
        var $mysqli;

        // Error handling variables
        var $errCatName;
        var $errLatitude;
        var $errLongitude;
        var $errImage;
        var $errPhone;
        var $errWebsite;
        var $succAddLoc;
        var $succAddCat;
        var $errEmail;
        var $errPass;
        var $succPass;
        var $succEmail;
        var $succEmailPass;
        var $succResetPass;
        var $errResetPass;
        var $errUsername;

        // Email configuration variables
        var $emailSubject;
        var $resetMessage;
        var $from;
        var $adminEmail;


        // Connect to database
        function __construct($host, $user, $pass, $database){
            // Connect to database
            $this->mysqli = new mysqli($host, $user, $pass, $database);

            if(mysqli_connect_errno($this->mysqli)){
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
            }

        }

        // Close database
        function close_database(){
            $this->mysqli->close();
        }

        // Validate username and password
        function validate_user($username, $password){
            ......
        }

        // Error handling label for reset password form
        function fill_error_pass($succResetPass, $errResetPass, $errUsername){
            ......
        }

        // Email message configuration
        function email_configuration($emailSubject, $resetMessage, $from, $adminEmail){
        .....
        }

        // Reset password
        function reset_password($username){
        .....
        }

        // Error handling label for add new location form
        function fill_error_location_data($errLatitude, $errLongitude, $errPhone, $errWebsite, 
                                 $errImage, $succAddLoc){
            $this->errLatitude = $errLatitude;
            $this->errLongitude = $errLongitude;
            $this->errPhone = $errPhone;
            $this->errWebsite = $errWebsite;
            $this->errImage = $errImage;
            $this->succAddLoc = $succAddLoc;

        }

        // Add new location
        function add_location($locationName, $address, $category,
                            $locImage, $lat, $lng, $tel, $url, $desc){

            // Create array variables to store multiple error
            $error = array();

            // Check if latitude is float
            $floatLat = floatVal($lat);
            if(!($floatLat && intVal($floatLat) != $floatLat)){
                $error['latitude'] = $this->errLatitude;
            }

            // Check if Longitude is float
            $floatLng = floatVal($lng);
            if(!($floatLng && intVal($floatLng) != $floatLng)){
               $error['longitude'] = $this->errLongitude;
            }

            // Validate phone number 
            if(empty($tel) || ($tel == "-")){
                $tel = "-";
            }else{
                $phonePattern = "/^[0-9()-]+$/";
                if(!preg_match($phonePattern, $tel)){ 
                    $error['phone'] = $this->errPhone;
                }
            }

            // Validate website
            if(empty($url) || ($url == "-")){
                $url = "-";
            }else{
                $urlPattern = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i";
                if (!preg_match($urlPattern, $url)){
                    $error['website'] = $this->errWebsite;
                }
            }

            // Check image file
            $allowedExts = array("jpeg", "jpg");
            $temp = explode(".", $locImage["name"]);
            $extension = end($temp);
            if (((($locImage["type"] == "image/jpeg")
            || ($locImage["type"] == "image/jpg"))
            || ($locImage["type"] == "image/pjpeg"))
            && ($locImage["size"] < 700000)
            && in_array($extension, $allowedExts)
            && !isset($error['latitude']) && !isset($error['longitude']) && !isset($error['phone']) && !isset($error['website'])){


                  // Create random image file name
                  $string = '0123456789';
                  $file = preg_replace("/\s+/", "_", $locImage['name']);
                  $imageUpload = date("Y-m-d")."-".$this->get_random_string($string, 4).".".$extension;

                  // Copy file to server directory
                  move_uploaded_file($locImage["tmp_name"],
                  "upload/images/" . $imageUpload);
                  $imageUpload = "upload/images/". $imageUpload;

                  $locationDate = date("Y-m-d");

                  // Add location data to tbl_location
                  $query = "INSERT INTO tbl_location 
                            (location_date, location_name, category_id, address, location_image,
                            latitude, longitude, phone, website, description)
                         VALUES ('$locationDate','$locationName', '$category', '$address', '$imageUpload',
                            $lat, $lng, '$tel', '$url', '$desc')";



                if($result = $this->mysqli->query($query)){

                    $error['result'] = $this->succAddLoc;
                }

            }else{

                $error['image'] = $this->errImage;

            }


            return $error;
        }

        // Get all locations data
        function get_all_locations(){

            .....
        }

        // Get all locations data for map
        function get_all_locations_map(){
        .....
        }

        // Get location data by id
        function get_location_by_id($id, $tag){
            .....
        }

        // Get location data to be displayed on location view page
        function get_location_view($id){

                // Get all locations data from tbl_location
                $query = "SELECT location_name, category_name, category_marker, address, location_image, latitude, longitude, phone, website, description
                        FROM tbl_location l, tbl_categories c
                        WHERE (l.category_id = c.category_id) AND (l.location_id = ?)";


                $stmt = $this->mysqli->stmt_init();
                if($stmt->prepare($query)) {    
                    // Bind your variables to replace the ?s
                    $stmt->bind_param('s', $id);
                    // Execute query
                    $stmt->execute();
                    // store result 
                    $stmt->store_result();
                    $stmt->bind_result($data['location_name'], 
                            $data['category_name'], 
                            $data['category_marker'], 
                            $data['address'], 
                            $data['location_image'],
                            $data['latitude'],
                            $data['longitude'],
                            $data['phone'],
                            $data['website'],
                            $data['description']
                            );
                    $stmt->fetch();
                    $stmt->close();
                }

            return $data;
        }

        // Delete location data
        function delete_location($id){
            ......

        }

        // Add new location
        function update_location($id, $locationName, $address, $category,
                            $locImage, $lat, $lng, $tel, $url, $desc, $previousImage){

            // Create array variables to handle multiple errors
            $error = array();

            // Check if latitude is float
            $floatLat = floatVal($lat);
            if(!($floatLat && intVal($floatLat) != $floatLat)){
                $error['latitude'] = $this->errLatitude;
            }

            // Check if Longitude is float
            $floatLng = floatVal($lng);
            if(!($floatLng && intVal($floatLng) != $floatLng)){
               $error['longitude'] = $this->errLongitude;
            }

            // Validate phone number 
            if(empty($tel) || ($tel == "-")){
                $tel = "-";
            }else{
                $phonePattern = "/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/";
                if(!preg_match($phonePattern, $tel)){ 
                    $error['phone'] = $this->errPhone;
                }
            }

            // Validate url
            if(empty($url) || ($url == "-")){
                $url = "-";
            }else{
                $urlPattern = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i";
                if (!preg_match($urlPattern, $url)){
                    $error['website'] = $this->errWebsite;
                }
            }

            // Check image location
            if(empty($locImage['name'])){
                if(!isset($error['latitude']) && !isset($error['longitude']) && !isset($error['phone']) && !isset($error['website'])){

                    // Add location data to database
                    $query = "UPDATE tbl_location 
                            SET location_name = '$locationName', 
                                category_id = '$category', 
                                address = '$address', 
                                latitude = '$lat', 
                                longitude = '$lng', 
                                phone = '$tel', 
                                website = '$url', 
                                description = '$desc'
                            WHERE location_id = '$id'";

                    if($result = $this->mysqli->query($query)){
                        $error['result'] = $this->succAddLoc;
                    }

                }
            }else{
                // Check image file
                $allowedExts = array("jpeg", "jpg");
                $temp = explode(".", $locImage["name"]);
                $extension = end($temp);
                if (((($locImage["type"] == "image/jpeg")
                || ($locImage["type"] == "image/jpg"))
                || ($locImage["type"] == "image/pjpeg"))
                && ($locImage["size"] < 700000)
                && in_array($extension, $allowedExts)
                && !isset($error['latitude']) && !isset($error['longitude']) && !isset($error['phone']) && !isset($error['website'])){

                      // Create random image file name
                      $string = '0123456789';
                      $file = preg_replace("/\s+/", "_", $locImage['name']);
                      $imageUpload = date("Y-m-d")."-".$this->get_random_string($string, 4).".".$extension;

                      // Copy file to server directory
                      move_uploaded_file($locImage["tmp_name"],
                      "upload/images/" . $imageUpload);
                      $imageUpload = "upload/images/". $imageUpload;

                        // Delete previous image
                        $delete = unlink("$previousImage");

                      // Add location data to database
                      $query = "UPDATE tbl_location 
                                SET location_name = '$locationName', 
                                    category_id = '$category', 
                                    address = '$address', 
                                    location_image = '$imageUpload',
                                    latitude = '$lat', 
                                    longitude = '$lng', 
                                    phone = '$tel', 
                                    website = '$url', 
                                    description = '$desc'
                                WHERE location_id = '$id'";

                    if($result = $this->mysqli->query($query)){
                        $error['result'] = $this->succAddLoc;
                    }

                }else{
                    $error['image'] = $this->errImage;

                }
            }

            return $error;
        }

        // Error handling label
        function fill_error_category_data($errCatName, $errImage, $succAddCat){
            $this->errImage = $errImage;
            $this->errCatName = $errCatName;
            $this->succAddCat = $succAddCat;
        }

        // Delete category
        function delete_category($id){
           ......

        }

        // Add new category
        function add_category($categoryName, $markerImage){

            // Get category data from tbl_categories
            $query = "SELECT * FROM tbl_categories 
                        WHERE category_name = '$categoryName'";

            if($result = $this->mysqli->query($query)){
                $row = $result->num_rows;
                $result->close();
            }

            // Create array variables to handle multiple array
            $error = array();

            // If category already exist in tbl_categories set the error
            if($row > 0){
                $error['name'] = $this->errCatName;
            }

            list($width, $height, $type, $attr) = getimagesize($markerImage["tmp_name"]);

            $allowedExts = array("png");
            $temp = explode(".", $markerImage["name"]);
            $extension = end($temp);
            if ((($markerImage["type"] == "image/x-png")
            || ($markerImage["type"] == "image/png"))
            && ($markerImage["size"] < 100000)
            && in_array($extension, $allowedExts)
            && (($width == 64) && ($height == 64))
            && !isset($error['name']) ){

                  // Create random image file name
                  $string = '0123456789';
                  $file = preg_replace("/\s+/", "_", $markerImage['name']);
                  $imageUpload = date("Y-m-d")."-".$this->get_random_string($string, 4).".".$extension;
                  // Copy image to server directory
                  move_uploaded_file($markerImage["tmp_name"],
                  "upload/markers/" . $imageUpload);
                  $imageUpload = "upload/markers/". $imageUpload;

                  // Add category to database
                $query = "INSERT INTO tbl_categories 
                            (category_name, category_marker)
                         VALUES ('$categoryName', '$imageUpload')";

                if($result = $this->mysqli->query($query)){
                    debug_to_console( $query);
                    $error['result'] = $this->succAddCat;
                }

            }else{
                $error['marker'] = $this->errImage;
            }


            return $error;
        }

        // Get all categories data
        function get_all_categories(){

            // Get categories data from database
            $query = "SELECT * FROM tbl_categories
                        ORDER BY category_id";

            $result = $this->mysqli->query($query);

            return $result;
        }

        // Get category data
        function get_category_by_id($id){
            .....
        }

        // Update category data
        function update_category($id, $previousName, $categoryName, $categoryMarker, $previousMarker){

           .......

    }

        // Create random name for image file
        function get_random_string($valid_chars, $length){

            $random_string = "";
            $num_valid_chars = strlen($valid_chars);

            for ($i = 0; $i < $length; $i++){
                $random_pick = mt_rand(1, $num_valid_chars);
                $random_char = $valid_chars[$random_pick-1];
                $random_string .= $random_char;
            }

            return $random_string;
        }

        // Error handling label
        function fill_error_settings($errEmail, $errPass, $succPass, $succEmail, $succEmailPass){
            $this->errEmail = $errEmail;
            $this->errPass = $errPass;
            $this->succPass = $succPass;
            $this->succEmail = $succEmail;
            $this->succEmailPass = $succEmailPass;
        }

        // Settings
        function settings($user, $email, $newPass, $confirmPass){

            .....
        }

    }
?>

Here is add_location_form.php

<?php 
    include('variables/variables.php'); 
    include('libs/pongodev.php');


    // Create object of pongodev class
    $objMap = new pongodev($host, $userdb, $passdb, $database);

    $result = 9999;

    // Get all category name
    $resultCategory = $objMap->get_all_categories();

    // Initialize location data
    $locationName = '';
    $address = '';
    $category = '';
    $image = '';
    $latitude = '';
    $longitude = '';
    $phone = '';
    $website = '';
    $description = '';

    // When user click on Submit button
    if(isset($_POST['btnSubmit'])){

        // Get location data
        $locationName = $_POST['locationName'];
        $address = $_POST['address'];
        $category = $_POST['category'];
        $image = $_FILES['image'];
        $latitude = $_POST['latitude'];
        $longitude = $_POST['longitude'];
        $phone = $_POST['phone'];
        $website = $_POST['website'];
        $description = $_POST['description'];

        // Create array variables
        $result = array();

        // Fill error label
        $objMap->fill_error_location_data($lblErrLatitude, $lblErrLongitude, $lblErrPhone, $lblErrWebsite, $lblErrImage, $lblAddLocSuccess);

        // Add location data to database
        $result = $objMap->add_location($locationName, $address, $category,
                                        $image, $latitude, $longitude,
                                        $phone, $website, $description);

    }
?>

<div class="content-container">
    <div class="row heading-container">
      <div class="col-xs* col-md-9">
        <h1><?php echo $lblAddNewLocation; ?></h1>
      </div>
  </div><!--/heading-container-->

<div class="clear"></div>

<form class="form-horizontal" role="form" method="post" enctype="multipart/form-data">

    <!-- Location name form -->
    <div class="form-group">
        <label for="inputLocationName" class="col-sm-2 control-label"><?php echo $lblName; ?></label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="inputLocationName" name="locationName" placeholder="<?php echo $lblName; ?>" value="<?php echo $locationName; ?>" required focus>
        </div><!--/span-->
    </div><!--/form-group-->
    <!--/Location name form -->

    <!-- Address form -->
    <div class="form-group">
        <label for="inputAddress" class="col-sm-2 control-label"><?php echo $lblAddress; ?></label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="inputAddress3" name="address" placeholder="<?php echo $lblAddress; ?>" value="<?php echo $address; ?>" required>
        </div><!--/span-->
    </div><!--/form-group-->
    <!--/Address form -->

    <!-- Category form -->
    <div class="form-group">
        <label for="inputCategory" class="col-sm-2 control-label"><?php echo $lblCategory; ?></label>
        <div class="col-sm-10">
            <select class="form-control" id="inputCategory" name="category" required>

                <?php while($data = mysqli_fetch_array($resultCategory)){ 
                    if($data['category_id'] == $category){?>                             
                        <option value="<?php echo $data['category_id']; ?>" selected><?php echo $data['category_name']; ?></option>
                    <?php }else{ ?>
                        <option value="<?php echo $data['category_id']; ?>"><?php echo $data['category_name']; ?></option>
                <?php } 
                }?>
            </select>
        </div><!--/span-->
    </div><!--/form-group-->
    <!--/Category form -->

    <!-- Latitude form -->
    <?php echo isset($result['latitude']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?>
        <label for="inputLatitude" class="col-sm-2 control-label"><?php echo $lblLatitude; ?></label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="inputLatitude" name="latitude" placeholder="<?php echo $lblLatitude; ?>" value="<?php echo $latitude; ?>" required>
            <span class="help-block"><em><?php echo isset($result['latitude']) ? $result['latitude']." ".$lblLatitudeHelp : $lblLatitudeHelp; ?></em></span>
        </div><!--/span-->
    </div><!--/form-group-->
    <!--/Latitude form -->

    <!-- Longitude form -->
    <?php echo isset($result['longitude']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?>
        <label for="inputLongitude" class="col-sm-2 control-label"><?php echo $lblLongitude; ?></label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="inputLongitude" name="longitude" placeholder="<?php echo $lblLongitude; ?>" value="<?php echo $longitude; ?>" required>
            <span class="help-block"><em><?php echo isset($result['longitude']) ? $result['longitude']." ".$lblLongitudeHelp : $lblLongitudeHelp; ?></em></span>
        </div><!--/span-->
    </div><!--/form-group-->
    <!--/Longitude form -->

    <!-- Image form -->
    <?php echo isset($result['image']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?>
        <label for="inputImage" class="col-sm-2 control-label"><?php echo $lblImage; ?></label>
        <div class="col-sm-10">
            <input type="file" class="form-control" id="inputImage" name="image" required>
            <span class="help-block"><em><?php echo isset($result['image']) ? $result['image']." ".$lblImageHelp : $lblImageHelp; ?></em></span>
        </div><!--/span-->
    </div><!--/form-group-->
    <!--/Image form -->

    <!-- Phone form -->
    <?php echo isset($result['phone']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?>
        <label for="inputPhone" class="col-sm-2 control-label"><?php echo $lblPhone; ?></label>
        <div class="col-sm-10">
            <input type="tel" class="form-control" id="inputPhone" name="phone" placeholder="<?php echo $lblPhone; ?>" value="<?php echo $phone; ?>">
            <span class="help-block"><em><?php echo isset($result['phone']) ? $result['phone']." ".$lblPhoneHelp : $lblPhoneHelp; ?></em></span>
        </div><!--/span-->
    </div><!--/form-group-->
    <!--/Phone form -->

    <!-- Website form -->
    <?php echo isset($result['website']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?>
        <label for="inputWebsite" class="col-sm-2 control-label"><?php echo $lblWebsite; ?></label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="inputWebsite" name="website" placeholder="<?php echo $lblWebsite; ?>" value="<?php echo $website; ?>">
            <span class="help-block"><em><?php echo isset($result['website']) ? $result['website']." ".$lblWebsiteHelp : $lblWebsiteHelp; ?></em></span>
        </div><!--/span-->
    </div><!--/form-group-->
    <!--/Website form -->

    <!-- Description -->
    <div class="form-group">
        <label for="inputDescription" class="col-sm-2 control-label"><?php echo $lblDescription; ?></label>
        <div class="col-sm-10">
            <textarea class="form-control" rows="3" id="inputDescription" name="description" placeholder="Description" required><?php echo $description; ?></textarea>
        </div><!--/span-->
    </div><!--/form-group-->
    <!--/Description -->

    <!-- if add data success show success alert, otherwise display error alert -->
    <?php if($result != 9999){
        if(isset($result['result'])){ ?>
        <div class="alert alert-success alert-dismissable">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <p><?php echo $result['result']; ?></p>
        </div>
    <?php }else{ ?>
        <div class="alert alert-danger alert-dismissable">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <p><?php echo $lblErrData; ?></p>
        </div>
    <?php }} ?>
    <!--/Adding result -->

    <!-- Submit button -->
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
                <button type="reset" class="btn btn-default"><?php echo $lblReset; ?></button>
                <button type="submit" class="btn btn-primary" name="btnSubmit"><?php echo $lblSubmit; ?></button>
        </div><!--/span-->
    </div><!--/form-group-->
    <!--/Submit button -->

    </form>
</div><!--/contain-container-->

<?php $objMap->close_database(); ?>
like image 316
Jiyda Moussa Avatar asked Nov 10 '22 12:11

Jiyda Moussa


1 Answers

Replace :

$image = $_FILES['image'];

with

$image = $_FILES['image']['name'];

if you want the image name
or :
with :

$image = $_FILES['image']['tmp_name'];


if you mean the file

like image 116
Stormix Avatar answered Nov 14 '22 22:11

Stormix