Skip to content
Advertisement

while uploading image in php shwoing error

I have an image upload option in my website, when the user upload the image, it goes to database and it should display in the homepage. I have done the following code:

for add.php

<?php
// Start session
session_start();

$postData = $imgData = array();

// Get session data
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';

// Get status message from session
if(!empty($sessData['status']['msg'])){
    $statusMsg = $sessData['status']['msg'];
    $statusMsgType = $sessData['status']['type'];
    unset($_SESSION['sessData']['status']);
}

// Get posted data from session
if(!empty($sessData['postData'])){
    $postData = $sessData['postData'];
    unset($_SESSION['sessData']['postData']);
}

// Get image data
if(!empty($_GET['id'])){
    // Include and initialize DB class
    require_once 'DB.class.php';
    $db = new DB();
    
    $conditions['where'] = array(
        'id' => $_GET['id'],
    );
    $conditions['return_type'] = 'single';
    $imgData = $db->getRows('images', $conditions);
}

// Pre-filled data
$imgData = !empty($postData)?$postData:$imgData;

// Define action
$actionLabel = !empty($_GET['id'])?'Edit':'Add';
?>

  <!-- Display status message -->
  <?php if(!empty($statusMsg)){ ?>
  <div class="col-xs-12">
    <div class="alert alert-<?php echo $statusMsgType; ?>">
      <?php echo $statusMsg; ?>
    </div>
  </div>
  <?php } ?>

  <div class="row">
    <div class="col-md-6">
      <form method="post" action="postAction.php" enctype="multipart/form-data">
        <div class="form-group">
          <label>Image</label>
          <?php if(!empty($imgData['file_name'])){ ?>
          <img src="uploads/images/<?php echo $imgData['file_name']; ?>">
          <?php } ?>
          <input type="file" name="image" class="form-control">
        </div>
        <div class="form-group">
          <label>Title</label>
          <input type="text" name="title" class="form-control" placeholder="Enter title" value="<?php echo !empty($imgData['title'])?$imgData['title']:''; ?>">
        </div>
        <a href="index.php" class="btn btn-secondary">Back</a>
        <input type="hidden" name="id" value="<?php echo !empty($imgData['id'])?$imgData['id']:''; ?>">
        <input type="submit" name="imgSubmit" class="btn btn-success" value="SUBMIT">
      </form>
    </div>
  </div>

for db.class.php which handles the operation:

<?php

class DB{
    private $dbHost     = "localhost";
    private $dbUsername = "root";
    private $dbPassword = "";
    private $dbName     = "sample";
    
    public function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
    
    
    public function getRows($table, $conditions = array()){
        $sql = 'SELECT ';
        $sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
        $sql .= ' FROM '.$table;
        if(array_key_exists("where",$conditions)){
            $sql .= ' WHERE ';
            $i = 0;
            foreach($conditions['where'] as $key => $value){
                $pre = ($i > 0)?' AND ':'';
                $sql .= $pre.$key." = '".$value."'";
                $i++;
            }
        }
        
        if(array_key_exists("order_by",$conditions)){
            $sql .= ' ORDER BY '.$conditions['order_by']; 
        }else{
            $sql .= ' ORDER BY id DESC '; 
        }
        
        if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
            $sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit']; 
        }elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
            $sql .= ' LIMIT '.$conditions['limit']; 
        }
        
        $result = $this->db->query($sql);
        
        if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
            switch($conditions['return_type']){
                case 'count':
                    $data = $result->num_rows;
                    break;
                case 'single':
                    $data = $result->fetch_assoc();
                    break;
                default:
                    $data = '';
            }
        }else{
            if($result->num_rows > 0){
                while($row = $result->fetch_assoc()){
                    $data[] = $row;
                }
            }
        }
        return !empty($data)?$data:false;
    }
    
    
    public function insert($table, $data){
        if(!empty($data) && is_array($data)){
            $columns = '';
            $values  = '';
            $i = 0;
            if(!array_key_exists('created',$data)){
                $data['created'] = date("Y-m-d H:i:s");
            }
            if(!array_key_exists('modified',$data)){
                $data['modified'] = date("Y-m-d H:i:s");
            }
            foreach($data as $key=>$val){
                $pre = ($i > 0)?', ':'';
                $columns .= $pre.$key;
                $values  .= $pre."'".$this->db->real_escape_string($val)."'";
                $i++;
            }
            $query = "INSERT INTO ".$table." (".$columns.") VALUES (".$values.")";
            $insert = $this->db->query($query);
            return $insert?$this->db->insert_id:false;
        }else{
            return false;
        }
    }
    
    
    public function update($table, $data, $conditions){
        if(!empty($data) && is_array($data)){
            $colvalSet = '';
            $whereSql = '';
            $i = 0;
            if(!array_key_exists('modified',$data)){
                $data['modified'] = date("Y-m-d H:i:s");
            }
            foreach($data as $key=>$val){
                $pre = ($i > 0)?', ':'';
                $colvalSet .= $pre.$key."='".$this->db->real_escape_string($val)."'";
                $i++;
            }
            if(!empty($conditions)&& is_array($conditions)){
                $whereSql .= ' WHERE ';
                $i = 0;
                foreach($conditions as $key => $value){
                    $pre = ($i > 0)?' AND ':'';
                    $whereSql .= $pre.$key." = '".$value."'";
                    $i++;
                }
            }
            $query = "UPDATE ".$table." SET ".$colvalSet.$whereSql;
            $update = $this->db->query($query);
            return $update?$this->db->affected_rows:false;
        }else{
            return false;
        }
    }
    
    
    public function delete($table, $conditions){
        $whereSql = '';
        if(!empty($conditions)&& is_array($conditions)){
            $whereSql .= ' WHERE ';
            $i = 0;
            foreach($conditions as $key => $value){
                $pre = ($i > 0)?' AND ':'';
                $whereSql .= $pre.$key." = '".$value."'";
                $i++;
            }
        }
        $query = "DELETE FROM ".$table.$whereSql;
        $delete = $this->db->query($query);
        return $delete?true:false;
    }
}

but when i am trying to upload the image, its showing

Sorry, there was an error uploading your file

the code which adds the image to table:

public function insert($table, $data){
        if(!empty($data) && is_array($data)){
            $columns = '';
            $values  = '';
            $i = 0;
            if(!array_key_exists('created',$data)){
                $data['created'] = date("Y-m-d H:i:s");
            }
            if(!array_key_exists('modified',$data)){
                $data['modified'] = date("Y-m-d H:i:s");
            }
            foreach($data as $key=>$val){
                $pre = ($i > 0)?', ':'';
                $columns .= $pre.$key;
                $values  .= $pre."'".$this->db->real_escape_string($val)."'";
                $i++;
            }
            $query = "INSERT INTO ".$table." (".$columns.") VALUES (".$values.")";
            $insert = $this->db->query($query);
            return $insert?$this->db->insert_id:false;
        }else{
            return false;
        }
    }

as am new to this can anyone please tell me what is wrong in my code, thanks in advance

Advertisement

Answer

It looks like you are trying to insert the image directly into the table. As per my experience till now, it doesn’t work that way.

The basic uploading of file in PHP is done by using the move_uploaded_file function. You can get more details Here.

When you upload a file in PHP through file HTML element then it’ll be uploaded to a temporary location and will provide you the details in the $_FILES array. You can find the complete file information such as file name, size, mime type, temp name and errors in the $_FILES array.

So what you should do is upload the file to a destination folder before inserting it to your database. So you need to create a function for upload:

function uploadFile($file) {
    $destination = "[YOUR DESTINATION FOLDER PATH]";
    if ($file['errors'] == 0) {
        $fileNameSplit = explode('.', $file['name']);
        $newFileName = $fileNameSplit[0] . time() . $fileNameSplit[1];
        $uploadPath = $destination . DIRECTORY_SEPARATOR . $newFileName;

        if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
            return $newFileName;
        }
    }

    return null;
}

You’ll have to call this function before your insert query. So your code will be like:

public function insert($table, $data){
    $uploadedFileName = uploadFile($_FILES['image']);
    if (!empty($uploadedFileName)) {
        $data['image'] = $uploadedFileName;
    }
    if(!empty($data) && is_array($data)){
        $columns = '';
        $values  = '';
        $i = 0;
        if(!array_key_exists('created',$data)){
            $data['created'] = date("Y-m-d H:i:s");
        }
        if(!array_key_exists('modified',$data)){
            $data['modified'] = date("Y-m-d H:i:s");
        }
        foreach($data as $key=>$val){
            $pre = ($i > 0)?', ':'';
            $columns .= $pre.$key;
            $values  .= $pre."'".$this->db->real_escape_string($val)."'";
            $i++;
        }
        $query = "INSERT INTO ".$table." (".$columns.") VALUES (".$values.")";
        $insert = $this->db->query($query);
        return $insert?$this->db->insert_id:false;
    }else{
        return false;
    }
}

Try this. There might be some minor modifications required in the code according to your logic. I have passed $_FILES['image'] as a parameter but you can also use the $_FILES array directly in the upload function without passing anything to it.

Also please note that you’ll have to use the same logic in the edit function as well but I guess you can do it. If not, let me know.

Hope this helps.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement