Home >Database >Mysql Tutorial >How to Upload Images to a MySQL Database Using PHP?
When attempting to upload images to a MySQL database using PHP, errors can arise if the image column in the database is not defined as a BLOB type. Ensuring that the image column is designated as BLOB will allow for the storage of binary data, including images.
Here is an example of updated PHP code for uploading images into a MySQL database:
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); // SQL Injection defense $image_name = addslashes($_FILES['image']['name']); $sql = "INSERT INTO `product_images` (`id`, `image`, `image_name`) VALUES ('1', '{$image}', '{$image_name}')"; // Execute the query if (!mysql_query($sql)) { echo "An error occurred while uploading the image."; } else { echo "Image uploaded successfully."; }
To specify the image type in the HTML form, use the enctype attribute with a value of multipart/form-data, as shown below:
<form action="insert_product.php" method="POST" enctype="multipart/form-data"> <label>File: </label> <input type="file" name="image"> <input type="submit" value="Upload"> </form>
The above is the detailed content of How to Upload Images to a MySQL Database Using PHP?. For more information, please follow other related articles on the PHP Chinese website!