Uncategorized

PHP MYSQL IMAGE UPLOAD CODE

In this article we will learn how to upload image using PHP and MYSQL


<?php

 
$servername = "localhost";
$username = "root";
$password = "";
$database = "db_name";

try {
  $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  //echo "Connected successfully";
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}
 


$allow = array("jpg", "JPG", "jpeg", "JPEG", "gif", "GIF", "png", "PNG", "pdf", "PDF");
  //1st File
  if($_FILES['photo1']['name'] == "") {
    //echo "No Image"
  } else {

    $photo1=basename($_FILES['photo1']['name']);
    $extension = pathinfo($photo1, PATHINFO_EXTENSION);
    if(in_array($extension,$allow)){
      $target_path = "../assets/img/trainers/";
      $photo1 = md5(rand() * time()).'.'.$extension;
      $target_path = $target_path . $photo1;
      move_uploaded_file($_FILES['photo1']['tmp_name'], $target_path);
      $image_1 = ($photo1!='')?" trainer_photo='$photo1' ". ',':'';
    }
  
  }


$insert_bookings = "UPDATE `$table_name` SET
   $image_1  
  col_1   = '".addslashes($col_a)."'
  where id='".$edit_id."'";   
  
  
$sql_insert = $dbconn->prepare($insert_bookings);
$sql_insert->execute();

?>


Simply replace the $target_path = “../assets/img/trainers/”; and trainer_photo which is the column name

Leave a Reply

Your email address will not be published. Required fields are marked *