Common mistakes commited in saving image path to a MySQL table - php

I am working on a php project. In one of the webpage I want to keep file upload option for users.
Here is my user input form
<?php
$db=mysqli_connect('localhost','test','test123','study')
?>
<form form action="" method="post" enctype="multipart/form-data">
<label for="file_array[0]">Photo :</label>
<input type="file" name="file_array[0]" accept=".jpeg" required />
<input type="file" name="file_array[1]" accept=".jpeg" required />
<label for="file_array[0]">ID Proof :</label>
<input type="submit" value="Upload All">
</form>
<?php
if(isset($_FILES['file_array'])){
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
for($i = 0; $i < count($tmp_name_array); $i++){
$v1=rand(1111,9999);
$v2=rand(1111,9999);
$v3=$v1.$v2;
$v3=md5($v3);
$upload_directory="uploads/";
$TargetPath=$v3.$name_array[$i];
if(move_uploaded_file($tmp_name_array[$i],
$upload_directory.$TargetPath))
{
$sql = "INSERT INTO customers (imagepath)
VALUES ("$upload_directory.$TargetPath")";
echo $name_array[$i]." upload is complete<br>";
}
else {
echo "failed to ".$name_array[$i]."
<br>";
}
}
}
?>
the problem is, Image gets successfully uploaded to the directory, but image path is not being saved into the database.
Any suggestion where I'm doing wrong in my code.

In the above code your not executing the query. It is just saved in $sql. refer below code:
if ($db->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
saving imagepath in db it also depends on the datatype as well.it will be text to save any length of data.

Related

Uploading Image in PHP page

Im currently in the process of creating a simple PHP website which can display a list of NBA teams and the respective players. One of the things I'm currently working on right now is adding the ability to upload images from the page itself instead of going to PHPMyAdmin.
Here's what the page looks like right now:
I'm trying to figure out how to add the team logo the same way I can add a new team name. As you can see in the bottom part there is an Add Team option which allows the user to add a new team and that team will be registered in the database.
I've tried to write some PHP code which enables the process of uploading images but have failed to do so.
team_list.php
<?php
error_reporting(0);
require_once('../Model/database.php');
// Get all categories
$query = 'SELECT * FROM categories
ORDER BY categoryID';
$statement = $db->prepare($query);
$statement->execute();
$teams = $statement->fetchAll();
$statement->closeCursor();
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image'];
// image file directory
$target = "images/".basename($image);
$sql = "INSERT INTO categories (img) VALUES ('$image')";
// execute query
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM categories");
?>
<!DOCTYPE html>
<html>
<!-- the head section -->
<head>
<title>NBA</title>
<link rel="stylesheet" type="text/css" href="../css/index.css">
<link rel="shortcut icon" type="image/png" href="images/favicon.ico"/>
</head>
<!-- the body section -->
<body>
<main>
<h1 id="addCategoryh1">Teams</h1>
<table id="categoryListTable">
<tr>
<th>Name</th>
<th> </th>
</tr>
<?php foreach ($teams as $team) : ?>
<tr>
<td><?php echo $team['categoryName']; ?></td>
<td>
<form action="delete_team.php" method="post"
id="delete_product_form">
<input type="hidden" name="team_id"
value="<?php echo $team['categoryID']; ?>">
<input id="deleteCategoryList" type="submit" value="Delete">
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<br>
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
echo "<img src='images/".$row['image']."' >";
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
<h2 id="add_category_h2">Add Team</h2>
<form action="add_team.php" method="post"
id="add_category_form">
<label>Name:</label>
<input type="input" name="name">
<input id="add_category_button" type="submit" value="Add">
</form>
<form method="POST" action="team_list.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<button type="submit" name="upload">POST</button>
</div>
</form>
<br>
<p>View Team List</p>
</main>
<footer id="categoryListFooter">
<p>© <?php echo date("Y"); ?> NBA</p>
</footer>
</body>
</html>
And this is the add_team.php file, which gets the data from database
<?php
// Get the team data
$name = filter_input(INPUT_POST, 'name');
// Validate inputs
if ($name == null) {
$error = "Invalid team data. Check all fields and try again.";
include('../Error/error.php');
} else {
require_once('../Model/database.php');
// Add the product to the database
$query = 'INSERT INTO categories (categoryName)
VALUES (:team_name)';
$query = "INSERT INTO categories (image) VALUES ('$fileName', '$content')";
$statement = $db->prepare($query);
$statement->bindValue(':team_name', $name);
$statement->execute();
$statement->closeCursor();
// Display the team List page
include('team_list.php');
}
?>
This is how the standing.php page looks like
updated add_team.php
// Get the team data
$name = filter_input(INPUT_POST, 'name');
// Validate inputs
if ($name == null) {
$error = "Invalid team data. Check all fields and try again.";
include('../Error/error.php');
} else {
require_once('../Model/database.php');
// Add the product to the database
$query = 'INSERT INTO categories (categoryName)
VALUES (:team_name)';
$query = "INSERT INTO categories (image) VALUES ('$fileName', '$content')";
$statement = $db->prepare($query);
$statement->bindValue(':team_name', $name);
$statement->execute();
$statement->closeCursor();
// Display the team List page
include('team_list.php');
// This is the directory where images will be saved
$target = "../images/";
$target = $target . basename( $_FILES['image']['name']);
// This gets all the other information from the form
$filename = basename( $_FILES['image']['name']);
$team_name = $_POST['team_name'];
// Write the file name to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['image']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
mysql_connect("renwid", "password") or die(mysql_error()) ;
mysql_select_db("nba") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO categories (img, team_name)
VALUES ('$filename', '$team_name')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
?>
You have to first upload successfully to the folder then you can add record in to your database
<?php
if(isset($_POST['submit'])) {
// This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['image']['name']);
// This gets all the other information from the form
$filename = basename( $_FILES['image']['name']);
$team_name = $_POST['team_name'];
// Write the file name to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['image']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
// mysql_connect("localhost", "root", "") or die(mysql_error()) ;
// mysql_select_db("your_db") or die(mysql_error()) ;
//Writes the information to the database
// mysql_query("INSERT INTO picture (image, team_name)
// VALUES ('$filename', '$team_name')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
?>
Your HTML should be
<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" id="image">
<input type="text" name="team_name" id="team_name">
<input type="submit" value="Submit" name="submit">
</form>
Refer https://github.com/aslamanver/nbaTest
You should create a uniqid when uploading the image, this way depending on how many people will upload images, if one were to upload the same image as another, it wouldn't be overwritten in the database
You can do this by using the explode and end function in PHP, also look into prepared statements when using SQL statements, this is to protect your DB against SQL injections, here's a good link:
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
The $_FILES has a few attributes including $_FILES["name"]["error"] which checks for errors, ideally you would make an if statement in which you specify the error condition for the file to uploaded to your DB. Also remember that you must first specify the directory before inserting it into your DB and if the file containing the code is in another folder, you use ../ to go back a directory.
When you display the image on your site you use this:
<img src="directory/<?php echo $row["row"]; ?>">

Insert Name of Pic Into MySQL

I have simple code to upload multi pics on my server.. Evrything works fine but I need to inesert picture names in MySql something like 1.png, 2.png, 3.png
Please for help.. I am still learning..
form.html
<form action="upload.php" method="post" enctype="multipart/form-data">
<p><input type="file" name="img[]"></p>
<p><input type="file" name="img[]"></p>
<p><input type="file" name="img[]"></p>
<input type="submit" value="Upload all files">
</form>
upload.php
<?php
if(isset($_FILES['img'])){
$name_array = $_FILES['img']['name'];
$tmp_name_array = $_FILES['img']['tmp_name'];
$type_array = $_FILES['img']['type'];
$size_array = $_FILES['img']['size'];
$error_array = $_FILES['img']['error'];
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "pics/".$name_array[$i])){
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
?>
Try this upload.php:
<?php
if(isset($_FILES['img'])){
foreach ($_FILES['img'] as $img) {
$name_array[] = $img['name'];
$tmp_name_array[] = $img['tmp_name'];
$type_array[] = $img['type'];
$size_array[] = $img['size'];
$error_array[] = $img['error'];
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "pics/".$name_array[$i])){
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
}
?>
Please save file name in loop like below
$file = rand(1000,100000)."-".$_FILES['file']['name'];
and then insert after upload
$sql="INSERT INTO tbl_uploads(file,type,size) VALUES('$file','$file_type','$file_size')";
mysql_query($sql);

How to insert multiple photos and multiple text fields into mysql database?

Plain and simple. I want to create a form that first of all inserts all fields values into the MySQL database. Second of all, I want to give users options to upload multiple images. but the code below wont insert image into the database. I am totally lost. don't know what else might be wrong with this code.
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post" enctype="multipart/form-data">
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<input type="FirstN" name="Firstname" >
<input type="LastN" name="Lastname" >
<input type="submit" value="Upload all files">
</form>
<?php
if(isset($_POST['submit'])) {
if(isset($_FILES['file_array'])) {
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
for($i = 0; $i < count($tmp_name_array); $i++) {
if(move_uploaded_file($tmp_name_array[$i], "test_uploads/".$name_array[$i])) {
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
$sql = "INSERT INTO image, FirstName, LastName VALUES ('{FirstN}','{LastN}','{file_array}')";
}
?>

Multitple Image upload can not save descriptions into database. How to fix this?

I am trying to create a multiple image upload with description on each image. I have used a jquery coe that allows me to add fields on demand. However, even though the images are uploaded and saved into DB, in the description column I get Array[0] instead of the actual description..
How can I fix this?
This is the HTML
<form action="upload.php" method="post" enctype="multipart/form-data">
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="file" name="file_array[]"><input type="text" name="description[]" placeholder="Write Description"></div>
</div>
<input type="submit" value="Upload all files">
</form>
and here is the upload.php
if(isset($_FILES['file_array'])){
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "upload/".$name_array[$i])){
mysql_query("INSERT into projects (`image`,`description`) VALUES('$name_array[$i]','$_POST[description][$i]') ");
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
You need to add your description in quotes. So your query would be.
mysql_query("INSERT into projects (`image`,`description`) VALUES('".$name_array[$i]."','".$_POST['description'][$i]."') ");

How to store image link in database php/mysql

I'm trying to allow an admin upload pictures of products in to the database, but I only want to store the link/url of the picture in the database and then store the uploaded file in a folder.
This is what I've got so far, and I keep getting "Sorry there was a problem uploading your file".
Here is the PHP code:
if ($_FILES['product_image']['error'] == 0) { // checking the file for any errors
$imgName = mysql_real_escape_string($_FILES['product_image']['name']); //returns the name of the image and stores it in variable $imgName
$imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); // returns the content of the file and stores it in $imgData
$imgType = mysql_real_escape_string($_FILES["product_image"]["type"]); //returns image/whatever the image type is
$targetFolder = "ProductImages/"; //directory where images will be stored...
$targetFolder = $targetFolder . basename($imgName); //adds the image name to the directory
}
$sql = "INSERT INTO products " . "(product_name,product_model,product_price,product_width,product_height,product_weight,product_quantity,product_category,product_subcategory, product_image, product_description,date_added) " . "VALUES('$product_name','$product_model','$product_price','$product_width','$product_height','$product_weight','$product_quantity', '$product_category', '$product_subcategory', '$imgName', '$product_description', NOW())";
//echo $sql;
mysql_select_db('online_store');
$result = mysql_query($sql, $conn);
$itemResult = "";
if (!$result) {
die('Could not enter data: ' . mysql_error());
}
$itemResult = "Product has been added";
if (move_uploaded_file($imgData, "$targetFolder" . $imgName)) { // writes/stores the image in the targetfolder->ProductImages
echo "The file " . basename($imgName) . "has been uploaded!";
} else {
echo "Sorry, there was a problem uploading your file!";
}
and the HTML form:
<form id="product_form" name="product_form" enctype="multipart/form-data" action="inventory_list.php" method="post">
<label for="product_image">Product Image*:</label> <input type="file" name="product_image"id="product_image"/>
</div>
<div>
<button name="add" id="add">Add Item</button>
</div>
</form
Use Sql Query Below.
$sql = "INSERT INTO products(`product_name`,`product_model`,`product_price`,`product_width`,`product_height`,`product_weight`,`product_quantity`,`product_category`,`product_subcategory`,`product_image`,`product_description`,`date_added`) VALUES('".$product_name."','".$product_model."','".$product_price."','".$product_width."','".$product_height."','".$product_weight."','".$product_quantity."', '".$product_category."', '".$product_subcategory."', '".$imgName."', '".$product_description."','".date("Y-m-d H:i:s")."')";
Also Change below line for upload image $imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); to $imgData = $_FILES["product_image"]["tmp_name"];
Try this Hope this helps.Not tested
<form id="product_form" name="product_form" enctype="multipart/form-data" method="post" action="" >
<label for="product_image">Product Image*:</label> <input type="file" name="product_image" id="product_image" />
</div>
<div>
<button name="add" id="add">Add Item</button>
</div>
</form>
PHP code :
<?php
if ($_FILES['product_image']['error'] == 0) { // checking the file for any errors
$imgName = mysql_real_escape_string($_FILES['product_image']['name']); //returns the name of the image and stores it in variable $imgName
$imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); // returns the content of the file and stores it in $imgData
$imgType = mysql_real_escape_string($_FILES["product_image"]["type"]); //returns image/whatever the image type is
$targetFolder = "ProductImages/"; //directory where images will be stored...
$targetFolder = $targetFolder . basename($imgName); //adds the image name to the directory
}
$sql = "INSERT INTO products " . "(product_name,product_model,product_price,product_width,product_height,product_weight,product_quantity,product_category,product_subcategory, product_image, product_description,date_added) " . "VALUES('$product_name','$product_model','$product_price','$product_width','$product_height','$product_weight','$product_quantity', '$product_category', '$product_subcategory', '$imgName', '$product_description', NOW())";
//echo $sql;
mysql_select_db('online_store');
$result = mysql_query($sql, $conn);
$itemResult = "";
if (!$result) {
die('Could not enter data: ' . mysql_error());
}
$itemResult = "Product has been added";
if (move_uploaded_file($imgData, $targetFolder)) { // writes/stores the image in the targetfolder->ProductImages
echo "The file " . basename($imgName) . "has been uploaded!";
} else {
echo "Sorry, there was a problem uploading your file!";
}
?>
First of all in HTML form action="post" is incorrect, the action attribute should contain a path. The method attribute should contain post or get like this: method="get" or method="post".

Categories