I am currently storing an image into the database directly. I learnt that it is not a good idea to store an image to database, instead i should upload the image to a directory and insert the file name to database. This is how i upload the image to directory.
<?php
$newImageSubmitted = isset( $_POST['new-image'] );
if ( $newImageSubmitted )
{
$output = upload();
}
return $output;
/function upload()
{
include_once "Uploader.class.php";
$uploader = new Uploader( "image-data" );
$uploader->saveIn("img");
$fileUploaded = $uploader->save();
if ( $fileUploaded )
{
$out = "<span class='rare'>Image uploaded success!!!..</span>";
} else {
$out = "something went wrong";
}
return $out;
}
and my form is as below:
<form method='post' action='upload.php' enctype='multipart/form-data' >
<label>Find a jpg image to upload</label>
<input type='file' name='image-data' accept='image/jpg'/>
<input type='submit' value='upload' name='new-image' />
</form>
Now how can i store the image name to database??:
$db = new mysqli("localhost", "root","","rec");
if ($db->connect_error) {
die("Connection failed this is the error: " . $db->connect_error);
}
$stmt = $db->prepare("INSERT INTO records (image) VALUES (?)");
if($stmt)
{
$stmt>bind_param("b",$newImageSubmitted);
$stmt->execute();
echo"<center>Image path stored.</center>";
}
here is uploader.class.php if required.
<?php
class Uploader {
private $filename;
private $fileData;
private $destination;
public function __construct( $key ) {
$this->filename = $_FILES[$key]['name'];
$this->fileData = $_FILES[$key]['tmp_name'];
}
public function saveIn( $folder ) {
$this->destination = $folder;
}
public function save(){
$folderIsWriteAble = is_writable( $this->destination );
if( $folderIsWriteAble ){
$name = "$this->destination/$this->filename";
$succes = move_uploaded_file( $this->fileData, $name );
} else {
trigger_error("cannot write to $this->destination");
$succes = false;
}
return $succes;
}
}