I know this is a long shot to ask but is their anyone that can show me how to upload an image to folder and image name to database? I have looked and everything I find is mysql. Mysql doesn't work for me I get many errors. Here is a code that I have but it will not work for me
<?php
$hostname_connect= "localhost";
$username_connect="torcdesi_barron7";
$password_connect= "Tazmania9292";
$database_connect="torcdesi_shirt";
// Create connection
$connect_solning = mysqli_connect($hostname_connect, $username_connect, $password_connect, $database_connect) or trigger_error(mysqli_error(),E_USER_ERROR);
mysqli_select_db($connect_solning ,$database_connect) or die (mysqli_error($connect_solning));
if($_POST)
{
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file"]["error"] > 0)
{
// if there is error in file uploading
echo "Return Code: " . $_FILES["file"]["error"] . "/>";
}
else
{
// check if file already exit in "images" folder.
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{ //move_uploaded_file function will upload your image.
if(move_uploaded_file($_FILES["file"] ["tmp_name"],"images/" . $_FILES["file"]["name"]))
{
// If file has uploaded successfully, store its name in data base
$query_image = "insert into shirt_table (image) values ('".$_FILES['file']['name']."', 'display','')";
if(mysqli_query($query_image))
{
echo "Stored in: " . "images/" . $_FILES["file"]["name"];
}
else
{
echo 'File name not stored in database';
}
}
}
}
}
?>
You have invalid query, you should use:
INSERT INTO table (field1, field2, field3) VALUES (value1, value2, value3)
You use instead:
INSERT INTO table (field1) VALUES (value1, value2, value3)
And empty quotes '' is a value too
Related
In this php code I want to customize the image upload destination. with this php file, I have directory called uploads. I want to add all my uploaded images to this directory and store path in db. how can I do this?
<?php
// Assigning value about your server to variables for database connection
$hostname_connect= "localhost";
$database_connect= "image_upload";
$username_connect= "root";
$password_connect= "";
$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
#mysql_select_db($database_connect) or die (mysql_error());
if($_POST) {
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file"]["error"] > 0) {
// if there is error in file uploading
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
} else {
// check if file already exit in "images" folder.
if (file_exists("images/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
//move_uploaded_file function will upload your image. if you want to resize image before uploading see this link http://b2atutorials.blogspot.com/2013/06/how-to-upload-and-resize-image-for.html
if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"])) {
// If file has uploaded successfully, store its name in data base
$query_image = "insert into acc_images (image, status, acc_id) values ('".$_FILES['file']['name']."', 'display','')";
if(mysql_query($query_image)) {
echo "Stored in: " . "images/" . $_FILES["file"]["name"];
} else {
echo 'File name not stored in database';
}
}
}
}
}
?>
currently when I run the upload
I am getting warnings
Warning: move_uploaded_file(images/1409261668002.png): failed to open stream: No such file or directory in D:\xampp\htdocs\image-upload\index.php on line 29
Warning: move_uploaded_file(): Unable to move 'D:\xampp\tmp\php1C1F.tmp' to 'images/1409261668002.png' in D:\xampp\htdocs\image-upload\index.php on line 29
You must specify a correct path, the 'images/1409261668002.png' path doesn't exist if you dont create them and don't specify them.
if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"]))) { .... }
You must specify the absolute path
You can use below code:
$image=basename($_FILES['file']['name']);
$image=str_replace(' ','|',$image);
$tmppath="images/".$image;
if(move_uploaded_file($_FILES['file']['tmp_name'],$tmppath))
{...}
Let me know if you have any query/concern regarding this.
Hello I have been writing a code for uploading a file to server
and store the values on the Mysql database
I am able to upload the file but facing issues in inserting the values in MYSQL server
I'm retrieving the values from an HTML Form and I'm successfully able to get the values and was able to echo from the file
Help is needed in inserting into table part of the code
<?php
require "test.php";
$username=$_POST['username'];
$filename=$_FILES['uploadedfile']['name'];
$language=$_POST['language'];
$comment=$_POST['comment'];
$user_id=$_POST['user_id'];
$filenames=$_FILES['uploadedfile']['name'];
$category=$_POST['category'];
$subcategory=$_POST['subcategory'];
$comment=$_POST['comment'];
$language=$_POST['language'];
$duration=$_POST['duration'];
$domain ='example.com/store/upload/';
$path=$domain.$category.'/'.$filenames;
//$path=$domain.$category.'/'.$filenames;
// Where the file is going to be placed
$target_path = "upload/".$category.'/';
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;
}
echo $filenames."<br />";
echo $domain."<br />";
echo $category."<br />";
echo $path."<br />";
echo $filename."<br />";
echo $language."<br />";
echo $comment."<br />";
echo $subcategory."<br />";
echo $duration."<br />";
echo $user_id."<br />";
// query
try{
$sql="INSERT INTO vup_file(filename,path,category,sub-category,user_id,comment,language,duration)
VALUES (:filename,:path,:category,:subcategory,:user_id,:comment,:language,:duration)";
$query=$conn->prepare($sql);
$query->execute(array(':filename'=>$filename,':path'=>$path,':category'=>$category,':subcategory'=>$subcategory,':user_id'=>$user_id,':comment'=>$comment,':language'=>$language,':duration'=>$duration));
echo 'Inserted';
}catch(PDOException $e)
{
echo 'ERROR OCCURED : '.$e->getMessage();
}
?>
Your sub-category column in your query, contains a hyphen. It needs to be escaped with backticks.
`sub-category`
Add $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); right after the connection is opened, which would have signaled the error.
SQL is evaluating it as a mathematical problem (minus).
Which translates to "sub" minus "category".
Another option you have is to simply rename your column to sub_category with an underscore, without the need to escape it.
An insight
If by chance your column is called sub_category instead of sub-category as shown in your query/question, then you will need to change it to sub_category in your query.
Or, if it's called subcategory. Only you know what your column is called.
I'm working on a website that takes a user uploaded video and puts the name, size, type, path, and tmp_name into a MySQL database. The upload.php file is below,
<?php
$is_form_submitted = (isset($_POST['submit']))?true:false;
if($is_form_submitted)
{
//defines variables
$name=$_FILES['file']['name'];
$type=$_FILES['file']['type'];
$size=$_FILES['file']['size'];
$tmp_name=$_FILES['file']['tmp_name'];
$target_path="videos/";
$allowedTypes = array("video/wmv","video/avi",
"video/mpeg","video/mpg","video/mp4");
$is_valid_type = (in_array($_FILES['file']['type'], $allowedTypes))?true:false;
if ( $is_valid_type&& ($_FILES["file"]["size"] < 20000000000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
mysql_query("INSERT INTO vids(name, type, size, tmp_name, target_path)
VALUES('$name', '$type', '$size', '$tmp_name', '$target_path')");
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"videos/" . $_FILES["file"]["name"]);
echo "Stored in: " . "videos/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
}
?>
And everything uploads properly but when I go and try to fetch the name and path of the video, it says that the video player has found no videos that are supported, so how would I fetch a random video from the database and put it as the source of the video player?
(the video file is playable in the player, so it is not the video's fault)
Here is the php code within the document code
<?php
$vid_url = "videos/";
$result = mysql_query("SELECT * FROM `vids` WHERE 1");
while($row = mysql_fetch_assoc($result))
{
echo
<div name="video">
<video width="100%" height="100%" controls>
<source src=".$vid_url.$row."type="video/mp4">
Error: Video Not working
</object>
</video>
</div>';
}
?>
And where I am storing the videos is a directory called videos
I figured it out in case anyone wants to reference this
<?php
//Connects to database
$host="################"; // Host name
$username="##########"; // Mysql username
$password="###########"; // Mysql password
$db_name="#######"; // Database name
$tbl_name="####"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
//Tells variable video where to get the name from
$vid_url = "videos/";
$result = mysql_query("SELECT * FROM vids ORDER BY RAND() LIMIT 1");
$row = mysql_fetch_assoc($result);
$video = $vid_url.$row["name"];
<?
SOLUTION: How to Save Uploaded File's Name on Database
this ended up helping me.
i am trying to add a file upload to a custom component using XML and database.
I know how to get file upload done in a static PHP environment but my knowledge
about the PHP MVC structure in joomla makes it so I am unable to add it.
What I have done so far:
• Added the field in the XML file (of the type file)
• Added the form fields in admin view project
• Added an extra field My_project table(same as the image upload column)
Until this point it works.(fields are shown in admin backend component)
Now when you save the document with a file uploaded in the admin back end it does not save it to the database.
if i put media as field type then it works, but when i change it to file it breaks down.
XML file
<?xml version="1.0" encoding="utf-8"?>
<form>
<fieldset>
<field name="project_file" type="file"
label="Upload file"
description="Upload file"
directory="mysites" />
<field name="main_image" type="media"
label="COM_MYSITES_FORM_LBL_PROJECT_MAIN_IMAGE"
description="COM_MYSITES_FORM_DESC_PROJECT_MAIN_IMAGE"
filter="raw"
directory="mysites" />
</fieldset>
PHP file upload script i normaly use
<?php
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
but what part goes in the model and what part goes in the controller?
and how to call it.
entire view is called in the controller
class MysitesControllerProject extends JControllerForm {
function __construct() {
$this->view_list = 'projects';
$jinput = JFactory::getApplication()->input;
$files = $jinput->files->get('jform');
$file = $files['project_file'];
$this->upload($file);
parent::__construct();
}
public function upload($files)
{
$file_name = $files['name'];
$src = $files['tmp_name'];
$size = $files['size'];
$upload_error = $files['error'];
$type = $files['type'];
$dest = "/home/vol3/byethost33.com/b33_13467508/bim-portfolio.cu.cc/htdocs/tmp";
if (isset( $file_name)) {
// Move the uploaded file.
JFile::upload( $src, $filepath );
}
}
}
Placing new field in database and XML form is only half of work. You also have to write file save/upload functionality. There are two places you can do it. In controller (for example save task procedure) or model (there are 2-3 functions where you can do it). Look into this file /administrator/components/com_media/controllers/upload.php (upload procedure). I would just extend your save function so before data will be saved into database file will be stored on file system. You can find original save function declaration in /libraries/legacy/controller/legacy.php (for Joomla 3.0.1, for other versions it shouldn't be hard to find)
Here is sample save function:
public function save($key = null, $urlVar = null){
// youre file upload code
return parent::save($key = null, $urlVar = null)
}
<?php
$file= $_FILES["file"]["name"];//file selected in form
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
move_uploaded_file($_FILES["file"]["tmp_name"],
"c:/EasyPHP-12.1/www/new website/upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "c:/EasyPHP-12.1/www/new website/upload/" . $_FILES["file"]["name"];
if(($_FILES['file']['size'] >0))
{echo 'imagetrue';$con=mysql_connect('localhost','abc','YES') or die ("con");;
$db=mysql_select_db("website",$con) or die ("db");
$query=mysql_query("insert into website.picture (imagew) values ('$file')") or die('query'); //storing in db}
//echo $_FILES['file']['error'] ;
$query2= mysql_query("select * from website.picture");
$res=mysql_fetch_array($query2);
foreach($res as $row){
$str = "c:/EasyPHP-12.1/www/new website/upload/ ".$row['imagew'];
echo '<img src="'.$str.'" alt="no">' ;}
?>
i am using this script to store image and then displaying it on webpage but it is not working it only displays empty thumbnails...
I'd be very suspect about using absolute paths like c:/EasyPHP-12.1/www/new website/upload/
I'f you're then accessing the page from http://127.0.0.1/new-website (which I presume you are - or something similar) then having windows system pathnames could be a problem - do browsers even read the local filesystem like that ?
Also, it makes it very un-portable for when you move it to another server.
I'd suggest $str = 'upload/'.$row['imagew']; So it's relative to the document hosted in (I presume) 127.0.0.1/new website/image-viewer.php (or whatever you called it)
Check the return value of move_uploaded_file() - if it's false then it has failed. If that's failing try using the relative path :
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
This again presumes your script is sitting in 127.0.0.1/new-website
EDIT - NOTE ::: Is your form using enctype="multipart/form-data" ? If it's not then the images never get to the server !