I'm trying to insert uploaded image into mysql with the user's user_id from session variable. I found an online tutorial and changed it as below:
<?php
require_once('../Login/includes/session_timeout_db.inc.php');
$dbuser="";
$dbname="";
$dbpass="";
$dbserver="";
$con = mysql_connect($dbserver,$dbuser,$dbpass);
if (!$con){ die('Could not connect: ' . mysql_error()); }
mysql_select_db($dbname, $con);
// Make sure the user actually
// selected and uploaded a file
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "INSERT INTO images, owner_id";
$query .= "(image) VALUES ('$data', '.$_SESSION['id'].')";
$results = mysql_query($query, $link);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
// Close our MySQL Link
mysql_close($link);
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8” />
<title>Manage Tasks</title>
<link rel="stylesheet" type="text/css" href="../allcss/style.css" />
</head>
<body>
<?php
require('../Login/includes/header.inc.php');
?>
<div id="content">
<form enctype="multipart/form-data" action="" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
</div>
</body>
</html>
I'm having and error on the second line of my query:
$query = "INSERT INTO images, owner_id";
$query .= "(image) VALUES ('$data', '.$_SESSION['id'].')";
$results = mysql_query($query, $link);
*the error is Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING on line 28*
could someone please help?
Thanks in adnvance
Your images field would need to be of type BLOB. Don't do this though, save your files in the filesystem and save the directory path to the image in your database.
change :
"(image) VALUES ('$data', '.$_SESSION['id'].')";
into :
"(image) VALUES ('$data', '".$_SESSION['id']."')";
Related
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"]; ?>">
This is the code for the upload form to enable me to upload an image to the database
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="file_uploader.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
This is the code that I have in a in a file called file_uploader.php. When trying to complete this I get the error Could not copy file!
<?php
if( $_FILES['file']['name'] != "" )
{
copy( $_FILES['file']['name'], "databasehostdetails" ) or
die( "Could not copy file!");
}
else
{
die("No file specified!");
}
?>
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name']; ?>
<li>File size: <?php echo $_FILES['file']['size']; ?> bytes
<li>File type: <?php echo $_FILES['file']['type']; ?>
</ul>
</body>
</html>
You need to use tmp_name. Also, what is databasehostdetails? The second parameter is the destination (where you want to copy the file to).
copy($_FILES['file']['tmp_name'], DESTINATION_PATH);
Here is a simple way to do this. I am giving you my script
index.html
But be carefull:
It is not recommended since it is to costly for your database to store files
Fix any sql injection vurnelabilities. I my self don't know how to do this. You can make a research and fix it.
Also check out here Storing Images in DB - Yea or Nay?
However the code works pretty good if it not a large scale application and no sql injection attacks could happen.
<html>
<body>
<form method="post" enctype="multipart/form-data" action="doupload.php">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
<input name="upload" type="submit" id="upload" value=" Upload ">
</form>
</body>
</html>
doupload.php
<?php
include("config.php");
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload set name='".$fileName."', size='".$fileSize."', type='".$fileType."', content='".$content."'";
mysql_query($query) ;
?>
getuploaded.php
<?php
// select records from database if exists to display
include("config.php");
$query1 = "SELECT id, name FROM upload";
$result1 = mysql_query($query1) or die('Error, query failed');
if(mysql_num_rows($result1)>0)
{
while(list($id, $name) = mysql_fetch_array($result1))
{
?>
<?php echo $name;?> <br>
<?php
}
}
?>
download.php
<?php
//header("Content-type: $type");
include("config.php");
$id = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM upload WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
?>
config.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'uploadfile';
mysql_select_db($dbname);
?>
Createing the table
CREATE TABLE upload (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
type VARCHAR(30) NOT NULL,
size INT NOT NULL,
content MEDIUMBLOB NOT NULL,
PRIMARY KEY(id)
);
I am currently working on a website that needs to upload the images of different products by its users. I am implementing it by using MySql database via php.
My code for a basic form for taking input from users is:
<form enctype="multipart/form-data" action="testimage1.php" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
My database table is:
mysql> CREATE TABLE tbl_images (
> id tinyint(3) unsigned NOT NULL auto_increment,
> image blob NOT NULL,
> PRIMARY KEY (id)
> );
testimage1.php has the following code:-
$username = "root";
$password = "";
$host = "localhost";
$database = "thinstrokes";
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db ($database);
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link) or die(mysql_error());
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
On submitting the form I am getting an error: No image selected/uploaded
I am not getting the error... and I've already asked for this before as:
mysql error during inserting a image in mysql database
How can I insert an image in a MySQL database using PHP?
But until now I am not successful in storing the image in the database.
Your script is working just fine, This is what I test:
<?
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
?>
<form enctype="multipart/form-data" action="" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
And it works just fine, if you want to see it in action I can send you the link.
It must be something else that is ruining your code (*note that I removed the DB queries to avoid getting mysql errors but the script was working even with them there.
//Here is the solution for your problem
<form enctype="multipart/form-data" action="" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
<?php
// connection to database
include 'includes/connection.php';
?>
<?php
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$result = mysql_query("INSERT INTO image (image)VALUES ( '$data')", $connection);
if(!$result)
{
die("Database query failed: ". mysql_error());
}
// Print results
print "Thank you, your file has been uploaded.";
}
else
{
print "No image selected/uploaded";
}
?>
<?php
//close connection
include 'includes/close.php';
?>
I have successfully created the PHP script for the user to upload files to a database and also to a folder on my localhost. Until the user refreshes the page they cannot see their uploaded image. Here is my code.
<?php
error_reporting(E_ALL & ~E_NOTICE);
//connect to database
$connection = mysql_connect("localhost", "root", "") or die("can't make connection : " . mysql_error());
$database = mysql_select_db ("uploads", $connection) or die ("Could not select database");
//save the name of image in table
$query = mysql_query("select * from tbl_img") or die(mysql_error());
//retrieve all image from database and store them in a variable
while($row = mysql_fetch_array($query))
{
$img_name = $row['img'];
$image = "<img src='site_images/$img_name' /><br />";
//store all images in one variable
$all_img = $all_img . $image;
}
?>
<html>
<body>
<h1>Your Images</h1>
<?php echo $all_img;?>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
Upload your image:<br />
<input name="img_field" type="file" id="img_field" /><br /><br />
<input type="submit" name="submit" id="submit" value="Submit" />
<?php
//get the posted image when the submit button is clicked
if(isset($_POST['submit']))
{
$file = $_FILES['img_field'];
$file_name = $_FILES['img_field']['name'];
$file_tmp_name = $_FILES['img_field']['tmp_name'];
//save the image in img table
//connect to database
$con = mysql_connect("localhost", "root", "") or die("can't make connection : " . mysql_error());
$db = mysql_select_db ("uploads", $con) or die ("Could not select database");
//save the name of image in table
$query = mysql_query("INSERT INTO tbl_img(img) VALUES('$file_name')") or die(mysql_error());
//upload images to this folder (complete path)
$path = "site_images/$file_name";
//use move_uploaded_file function to upload or move file to the given folder or path
if(move_uploaded_file($file_tmp_name, $path))
{
echo "File Successfully uploaded";
}
else
{
echo "Please select a file";
}
}
?>
Any help would be much appreciated, thanx :)
I am making a gallery that uses a MySQL database (yeah I know it's a bad practice but it's the requirement for the moment.) I can upload multiple images but I'm having trouble displaying all images stored inside the database. The FORM allows five images to be uploaded. Then the user must proceed to another page where all the images in database (including the ones uploaded recently) will be displayed together with the description of the images. I have code already but the one that will work on the display is not working or I think is wrong.
Here is the form code:
<html>
<head>
<title> Upload image</title>
</head>
<body>
<div align="center">
<form action="fUpload.php" method="POST" enctype="multipart/form-data">
All forms must be filled. <br />
File: <br />
<input type="file" name="image[]"/> <input type="text" name="imageDescription[]" size="30" /> <br />
<input type="file" name="image[]"/> <input type="text" name="imageDescription[]" size="30" /> <br />
<input type="file" name="image[]"/> <input type="text" name="imageDescription[]" size="30" /> <br />
<input type="file" name="image[]"/> <input type="text" name="imageDescription[]" size="30" /> <br />
<input type="file" name="image[]"/> <input type="text" name="imageDescription[]" size="30" /> <br />
<input type="submit" value="Upload image" />
</form>
</div>
</body>
</html>
Here is the script that would upload:
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
//file properties//
$file = $_FILES['image']['tmp_name'];
echo '<br />';
/*if(!isset($file))
echo "Please select your images";
else
{
*/for($count = 0; $count < count($_FILES['image']); $count++)
{
//$image = file_get_contents($_FILES['image']['tmp_name']);
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]); echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results)
echo "Problem uploding the image. Please check your database";
//else
//{
echo "";
//$last_id = mysql_insert_id();
//echo "Image Uploaded. <p /> <p /><img src=display.php? id=$last_id>";
//header('Lcation: display2.php?id=$last_id');
}
//}
}
mysql_close($con);
header('Location: fGallery.php');
?>
And finally the one that should display:
<html>
<body>
</body>
<?php
//connect to the database//
mysql_connect("localhost","root", "") or die(mysql_error());
mysql_select_db("imagedatabase") or die(mysql_error());
//requesting image id
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM images WHERE id = $id");
while($datum = mysql_fetch_array($image, MYSQL_ASSOC))
{
printf("Description %s $image = $image['image'];
header("Content-type: image/jpeg");
}
mysql_close();
?>
Your help is much appreciated. I need it badly to move on.
From what i understand from your post is that uploading and storing isn't a problem, but showing the images is. That's probably because you're using vars that are not set, so no results kan be found in the database. If i misunderstood let me know.
<?php
// No ID
$image = mysql_query("SELECT * FROM images ORDER BY id DESC");
?>
Also look at what Prof83 says. Ignore my post if your script works with just one image.
Last but not least, if you're using different filetypes, also echo the correct MIME format in the header.
Update
I combined both answers.
Edit your loop:
<?php
while($row = mysql_fetch_assoc($image))
{
echo '<img src="img.php?id='.$row["id"].'">';
}
?>
Create a page name img.php
<?php
$query = mysql_query("SELECT image FROM images WHERE id = ".$_GET['id']);
$row = mysql_fetch_assoc($query);
header("Content-type: image/jpeg");
echo $row['image'];
?>
Ok you can't display multiple images within a image/jpeg page...
You're telling the browser that the page is image/jpeg (in other words, the page is AN IMAGE) but you're echoing out multiple image data
You should rather use the gallery page to show all images like this:
<?php
// $images = result from database of all image rows
foreach ($images as $img) echo '<img src="img.php?id='.$img["id"].'">';
?>
and in img.php:
// Load the image data for id in $_GET['id'];
header("Content-type: image/jpeg");
echo $data;