PHP OOP CRUD Tutorial – Step By Step Guide! Part 10
Dodato 2 months ago u OOP PHP od Milan Janković

PHP OOP CRUD Tutorial – Step By Step Guide! Part 10

11.3 Change create() method

Open "objects" folder and open the "product.php" file inside it. Find the "create()" method.

Add the "image" field by changing the query to:

// insert query

$query = "INSERT INTO " . $this->table_name . "

            SET name=:name, price=:price, description=:description,

                category_id=:category_id, image=:image, created=:created";

On the sanitize section, it will be:

$this->image=htmlspecialchars(strip_tags($this->image));

Then bind the value.

$stmt->bindParam(":image", $this->image);

Add the "image" property at the top of the class, maybe after public $category_id;

public $image;

Using the PhpMyAdmin, add an "image" field in the products table. Set the type to VARCHAR with 512 in length.

11.4 Call uploadPhoto() method

Open create_product.php and find this line.

// product was created in database

echo "<div class='alert alert-success'>Product was created.</div>";

Put the following code under the code above. This will call the uploadPhoto() method that will try to upload the file to server.

// try to upload the submitted file

// uploadPhoto() method will return an error message, if any.

echo $product->uploadPhoto();

11.5 Add uploadPhoto() method

The previous section will not work without the complete code of uploadPhoto() method.

Open "objects" folder and open the "product.php" file inside it. Add the following method inside the class.

// will upload image file to server

function uploadPhoto(){

 

    $result_message="";

 

    // now, if image is not empty, try to upload the image

    if($this->image){

 

        // sha1_file() function is used to make a unique file name

        $target_directory = "uploads/";

        $target_file = $target_directory . $this->image;

        $file_type = pathinfo($target_file, PATHINFO_EXTENSION);

 

        // error message is empty

        $file_upload_error_messages="";

 

    }

 

    return $result_message;

}

11.6 Validate submitted file

Now we will validate the submitted file by:

  • Identifying if it's a real or fake image.
  • Limit the allowed file types.
  • Prevent multiple file on the server.
  • Deny uploading files with large file size.
  • Making sure the "uploads" directory exists.

Add the following code after $file_upload_error_messages=""; of the previous section.

// make sure that file is a real image

$check = getimagesize($_FILES["image"]["tmp_name"]);

if($check!==false){

    // submitted file is an image

}else{

    $file_upload_error_messages.="<div>Submitted file is not an image.</div>";

}

 

// make sure certain file types are allowed

$allowed_file_types=array("jpg", "jpeg", "png", "gif");

if(!in_array($file_type, $allowed_file_types)){

    $file_upload_error_messages.="<div>Only JPG, JPEG, PNG, GIF files are allowed.</div>";

}

 

// make sure file does not exist

if(file_exists($target_file)){

    $file_upload_error_messages.="<div>Image already exists. Try to change file name.</div>";

}

 

// make sure submitted file is not too large, can't be larger than 1 MB

if($_FILES['image']['size'] > (1024000)){

    $file_upload_error_messages.="<div>Image must be less than 1 MB in size.</div>";

}

 

// make sure the 'uploads' folder exists

// if not, create it

if(!is_dir($target_directory)){

    mkdir($target_directory, 0777, true);

}

11.7 Return error messages

If the file is valid, we will upload the file to server. Specifically, in the "uploads" folder. If there's any error, we will return it to be shown to the user.

Place the following code after the previous section's code.

// if $file_upload_error_messages is still empty

if(empty($file_upload_error_messages)){

    // it means there are no errors, so try to upload the file

    if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)){

        // it means photo was uploaded

    }else{

        $result_message.="<div class='alert alert-danger'>";

            $result_message.="<div>Unable to upload photo.</div>";

            $result_message.="<div>Update the record to upload photo.</div>";

        $result_message.="</div>";

    }

}

 

// if $file_upload_error_messages is NOT empty

else{

    // it means there are some errors, so show them to user

    $result_message.="<div class='alert alert-danger'>";

        $result_message.="{$file_upload_error_messages}";

        $result_message.="<div>Update the record to upload photo.</div>";

    $result_message.="</div>";

}

11.8 Show uploaded image file

Open "objects" folder and open "product.php" file. Find readOne() method. Add the "image" field in the method. The new method should look like the following.

function readOne(){

 

    $query = "SELECT name, price, description, category_id, image

        FROM " . $this->table_name . "

        WHERE id = ?

        LIMIT 0,1";

 

    $stmt = $this->conn->prepare( $query );

    $stmt->bindParam(1, $this->id);

    $stmt->execute();

 

    $row = $stmt->fetch(PDO::FETCH_ASSOC);

 

    $this->name = $row['name'];

    $this->price = $row['price'];

    $this->description = $row['description'];

    $this->category_id = $row['category_id'];

    $this->image = $row['image'];

}

Open read_one.php file and find the closing "tr" tag of the "Category" field in the HTML table. Add the following code. This will show the uploaded image.

echo "<tr>";

    echo "<td>Image</td>";

    echo "<td>";

        echo $product->image ? "<img src='uploads/{$product->image}' style='width:300px;' />" : "No image found.";

    echo "</td>";

echo "</tr>";

11.9 Output

Click the "Create" button, you will see something like the image below.

When you submitted the form, it will show a message prompt.

If you tried to upload an invalid image file, for example a PDF file. It will show an error message.

If you click the "Read" button of a record with an image, it will look like the following.

If the record has no image, it will say "No image found." message.

Ostavite komentar

Treba vam web sajt ?

Kontakt