article

Tuesday, April 2, 2024

PHP and MySQL Upload Image

PHP and MySQL Upload Image

Bootstrap 5 https://getbootstrap.com/docs/5.1/getting-started/download/
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
//index.php
<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>PHP and MySQL Upload Image</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <style>
        .image-preview {
            background-image: url('avatar.png');
            width: 14%;
            height: 100px;
            background-size: cover;
            background-position: center;
            border-radius: 10px;
        }
 
        .photo {
            width: 50px;
            height: 50px;
            border-radius: 50%;
        }
    </style>
</head>
 
<body>
    <?php
    include "dbcon.php";
    $sql = "select * from users order by name";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $result = $stmt->get_result();
    include "upload.php";
    ?>
    <div class="container">
        <h1 class="mb-5">PHP and MySQL Upload Image</h1>
        <div class="table-responsive">
            <h2>List of users</h2>
            <a class="btn btn-primary" href="#" data-bs-toggle="modal" data-bs-target="#modalAddnew">Add New</a>
 
            <table class="mt-5 table table-bordered table-striped">
                <thead>
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Name</th>
                        <th scope="col">Photo</th>
                        <th scope="col">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if ($result->num_rows > 0) {
                        $counter = 0;
                        foreach ($result as $row) {
                            $counter++;
                    ?>
                            <tr class="">
                                <td scope="row"><?= $counter ?></td>
                                <td><?= $row['name'] ?></td>
                                <td><img class="photo" src="uploads/<?= $row['photo'] ?>"></td>
                                <td>
                                    <a href="index.php?id=<?= $row['id'] ?>" onclick="return confirm('Are you sure you want to delete the user?')">
                                        <button type="button" class="btn btn-danger" title="delete the user">
                                            Delete
                                        </button>
                                    </a>
                                </td>
                            </tr>
                        <?php }
                    } else { ?>
                        <tr>
                            <td>No users to display</td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
 
    <!-- Modal -->
    <div class="modal fade" id="modalAddnew" tabindex="-1" role="dialog" aria-labelledby="modalTitleId" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitleId">
                        Add New
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form action="" method="post" enctype="multipart/form-data">
                        <div class="mb-3">
                            <label for="name" class="form-label">Name</label>
                            <input type="text" class="form-control" name="name" id="name" aria-describedby="helpId" placeholder="Enter a Name" />
                            <div class="text-danger"><?= $name_err ?></div>
                        </div>
                        <div class="mb-3">
                            <label for="photo" class="form-label">Select A Photo</label>
                            <input type="file" class="form-control" name="photo" id="photo" placeholder="" aria-describedby="fileHelpId" onchange="previewImg(this)" />
                            <div id="fileHelpId" class="form-text">Allowed file types: jpg, jpeg, png</div>
                            <div class="text-danger"><?= $photo_err ?></div>
                        </div>
                        <div class="mb-5 image-preview"></div>
                        <button type="submit" name="submit" class="btn btn-primary">
                            Submit
                        </button>
                    </form>
                    <div class="text-danger"><?= $err_msg ?></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        Close
                    </button>
                </div>
            </div>
        </div>
    </div>
    <script>
        function previewImg(input) {
            if (input.files && input.files[0] != "") {
                var reader = new FileReader();
                reader.onload = function(e) {
                    $(".image-preview").css('background-image', 'url(' + e.target.result + ')');
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
</body>
 
</html>
dbcon.php
1
2
3
4
5
6
7
8
9
10
11
//dbcon.php
<?php
 
$server = "localhost";
$uid = "root";
$pwd = "root";
$dbname = "devproject";
$conn = new mysqli($server, $uid, $pwd, $dbname);
 
if ($conn->connect_error)
    die("database connection error " . $conn->connect_error);
upload.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//  upload.php
<?php
$error = false;
$name_err = $photo_err = $err_msg = "";
$valid_ext = array('jpg', 'jpeg', 'png');
 
$target_dir = "uploads/";
$photo = "";
 
if (isset($_REQUEST['id']) && $_REQUEST['id'] != "") {
    // delete image
    $id = $_REQUEST['id'];
 
    $sql = "select photo from users where id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows == 1) {
        $row = $result->fetch_assoc();
        $photo = $row['photo'];
    }
 
    if (file_exists($target_dir . $photo))
        unlink($target_dir . $photo);
 
    $sql = "delete from users where id=?";
    $stmt->prepare($sql);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    header("location:index.php");
}
 
if(isset($_POST['submit'])){
    $name = $_POST['name'];
 
    if ($name ==""){
        $name_err = "Please enter the name";
        $error = true;
    }
 
    if($_FILES['photo']['name'] ==""){
        $photo_err = "Please select a photo";
        $error = true;
    }
 
    if (!$error){
        $image_name = $_FILES['photo']['name'];
        $image_tmp = $_FILES['photo']['tmp_name'];
        $image_size = $_FILES['photo']['size'];
 
        // check for extension
 
        $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
        if (in_array($ext, $valid_ext)) {
            // valid extension
            if (exif_imagetype($image_tmp) == IMAGETYPE_JPEG || exif_imagetype($image_tmp) == IMAGETYPE_PNG) {
                // valid image
                if ($image_size > 4000000) {
                    // exceeds 4M
                    $err_msg = "image size exceeds 4M";
                } else {
                    // upload
                    $new_image = time() . "-" . basename($image_name);
 
                    try {
                        move_uploaded_file($image_tmp, $target_dir . $new_image);
 
                        // insert
                        try {
                            $sql = "insert into users (name, photo) values (?, ?)";
                            $stmt = $conn->prepare($sql);
                            $stmt->bind_param("ss", $name, $new_image);
                            $stmt->execute();
                            header("location:index.php");
                        } catch (Exception $e) {
                            $err_msg = $e->getMessage();
                        }
                    } catch (Exception $e) {
                        $err_msg = $e->getMessage();
                    }
                }
            } else {
                $err_msg = "Not a valid image file";
            }
        } else {
            $err_msg = "Not a valid extension";
        }
    }
 
}
Github - PHP and MySQL Upload Image

Related Post