Adding file name to database without uploading it - php

I'm making a system for adding files to a database. I use a form:
<form action="insert.php" method="post" enctype="multipart/form-data">
Fil: <input type="file" name="file" id="file">
Titel: <input type="text" name="titel" /><br />
Längd (min): <input type="text" name="langd" /><br />
Medverkande: <input type="text" name="medverkande" /><br />
Reporter: <input type="text" name="reporter" /><br />
Fotograf: <input type="text" name="fotograf" /><br />
Sökord: <input type="text" name="sokord" /><br />
<input type="submit" />
</form>
The code in insert.php:
<?php
$con = mysql_connect("database","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("165666-kltvplay", $con);
$filnamn = $_FILES["file"]["name"] ;
$sql="INSERT INTO Blad1 (ProgramID, Titel, Langd, Medverkande, Reporter, Fotograf, Sokord)
VALUES
('$filnamn','$_POST[titel]','$_POST[langd]','$_POST[medverkande]','$_POST[reporter]','$_POST[fotograf]','$_POST[sokord]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "En ny film inlagd: <br> ";
echo $filnamn;
mysql_close($con);
?>
But when I add the file it seems to be uploading the whole file because there is a % counter in my browser and it's taking a loooong time to complete(the files are qute big). I just want the name of the file inserted into the database (and that is working) but not to upload the whole file.
And is it possible to add just the name and not the file exetension?

You'll have to do some JavaScript magic. Once the user has selected a file, you can read the file name:
var fileName = document.getElementById('file').value;
Then put that value into a hidden input field (that is inside your form):
document.getElementById('hidden-filename').value = fileName;
Then hook into the form's submit event and remove the file input so it won`t get submitted.
On the server you read the value of the hidden-filename (or whatever the name) and insert it into the DB.
Be warned though that not all browsers will return the actual file path. The name of the file will be correct, but the path may not be.
Also note that you won't be able to do anything with this file then (on the server or on the client).
AS for the last question you had (no extension), look at this: PHP, get file name without file extension

Related

connect form page on wordpress with php file

I created form on one page in my wordpress:
<form action="scores_send.php" method="post">
<strong>Date: </strong><input type="date" name="date" /><br />
<strong>TEAM 1:</strong>
Player 1.: <input type="text" name="team1_player1" /><br />
Player 2.: <input type="text" name="team1_player2" /><br />
<strong>TEAM 2:</strong>
Player 1.: <input type="text" name="team2_player1" /><br />
Player 2.: <input type="text" name="team2_player2" /><br />
<strong>SCORE:</strong>
Team 1. <input type="number" name="score_team1" min="0" max="5"/> : <input type="number" name="score_team2" min="0" max="5"/> Team 2.<br />
<input type="submit" value="Add" />
</form>
And also I wrote php code which connect to my external (no-wordpress) postgres database (connection parameters in code are not true) and insert information from form to one table:
<?php
$date = $_POST['date'];
$t1p1 = $_POST['team1_player1'];
$t1p2 = $_POST['team1_player2'];
$t2p1 = $_POST['team2_player1'];
$t2p2 = $_POST['team2_player2'];
$score1 = $_POST['score_team1'];
$score2 = $_POST['score_team2'];
if($date and $t1p1 and $t1p2 and $t2p1 and $t2p2 and $score1 and $score2) {
$connection = pg_connect("host=127.0.0.1 port=5432 dbname=scores user=user password=pass")
or die('Brak polaczenia z serwerem PostgreSQL');
$db = #pg_select_db('scores', $connection)
or die('Nie moge polaczyc sie z baza danych');
$team1 = #pg_query("INSERT INTO scores.games (score_team1, score_team2, datetime, team1_player1, team1_player2, team2_player1, team2_player2) VALUES ('$score1', '$score2', '$date', '$t1p1', '$t1p2', '$t2p1', '$t2p2'");
if($team1) echo "Scores added.";
else echo "ERROR! Scores not added";
pg_close($connection);
}
?>
I tried 2 ways:
1. to create template php file in folder of my theme and
2. to paste this code to content editor in wordpress (using this plugin: https://wordpress.org/plugins/insert-php/)
and both ways is not working. I changed part "action" in , but maybe wrong.
Just change your action of your form to : http://yoursite.com/scores_send.php
make sure that your scores_send.php is on the root of your installation.
So, your form look like :
<form action="http://yoursite.com/scores_send.php" method="post">
You should use http://example.com/page-slug/ in form action
Where page-slug is the slug of another page create by make scores_send.php as template.It will post all form value to score_send.php.From where you can proceed further to insert into external DB.
<form action="http://example.com/page-slug/" method="post">

Error in code to upload file via php and html form

I am experiencing an error with the following code whereby the file fails to upload to the server. Can someone please take a look at the two files and advise where I have got it wrong, I know I have probably been thick but any help would be greatly appreciated.
The files are on a small internal intranet so I am not concerned with the fact I am putting the database connection and password into the file.
As I said any help would be greatly appreciated as I am only receiving the final sorry error and no information is being passed to the MySQL database. I can get the form and code to work fine without the upload but not with.
I have checked the upload directory and permissions for access to it and all are ok.
the html form:
<form enctype="multipart/form-data" action="add.php" method="POST">
Model:<br /> <input type="text" name="model"><br>
Size:<br /> <input type="text" name="size"><br>
Total width:<br /> <input type="text" name="tot_width"><br>
Internal width:<br /> <input type="text" name="int_width"><br>
Total height:<br /> <input type="text" name="tot_height"><br>
Frame height:<br /> <input type="text" name="fra_height"><br>
Total depth:<br /> <input type="text" name="tot_depth"><br>
Seat height:<br /> <input type="text" name="sea_height"><br>
Seat depth:<br /> <input type="text" name="sea_depth"><br>
Arm height:<br /> <input type="text" name="arm_height"><br>
Std leg height:<br /> <input type="text" name="std_leg_height"><br>
Image:<br /> <input type="file" name="image"><br>
<input type="submit" value="Add">
</form>
The PHP:
//This is the directory where images will be saved
$target = "/images/product";
$target = $target . basename( $_FILES['image']['name']);
//Get all the other information from the form
$model=$_POST['model'];
$size=$_POST['size'];
$totWidth=$_POST['tot_width'];
$intWidth=$_POST['int_width'];
$totHeight=$_POST['tot_height'];
$fraHeight=$_POST['fra_height'];
$totDepth=$_POST['tot_depth'];
$seaHeight=$_POST['sea_height'];
$seaDepth=$_POST['sea_depth'];
$armHeight=$_POST['arm_height'];
$stdLegHeight=$_POST['std_leg_height'];
$pic=($_FILES['image']['name']);
// Connect to Database
mysql_connect("localhost", "databaseUser", "databasePassword") or die(mysql_error()) ;
mysql_select_db("databaseName") or die(mysql_error()) ;
//Write information to the database
mysql_query("INSERT INTO `prod_dims` VALUES '$model', '$size', '$totWidth', '$intWidth', '$totHeight', '$fraHeight', '$totDepth', '$seaHeight', '$seaDepth', '$armHeight', '$stdLegHeight', '$pic'") ;
//Put the image on the server
if(move_uploaded_file($_FILES['image']['name'], $target))
{
//Is the upload ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Give an error if its not
echo "Sorry, there was a problem uploading your file.";
}
change
if(move_uploaded_file($_FILES['image']['name'], $target))
to
if(move_uploaded_file($_FILES["image"]["tmp_name"], $target))

How to write a javascript button which contains data?

How do you create a javascript button to take the information from the form to the php sql:
<form>
<input type="text" placeholder="Name" name="name" class="name" /></br>
<input type="text" placeholder="Phone Number" name="number" class="number"/></br>
<input type="text" placeholder="Location " name="location" class="location"/></br>
<input type="submit" value="Add Booking" />
</form>
?php
$name = $_GET['name'];
$number = $_GET['number'];
$location = $_GET['location'];
$con = mysql_connect(".....",".....",".....");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
("chanh", $con);
$sql ="INSERT INTO book (name, number, location,timestamp)
VALUES ('$name', '$number','$location',NOW())";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added"
mysql_close($con);
?>
Any help would be appreciated as I am just a rookie! Thanks
You just need to specify where you form will be submitted
<form action="submit.php" method="get">
<input type="text" placeholder="Name" name="name" class="name" /></br>
<input type="text" placeholder="Phone Number" name="number" class="number"/></br>
<input type="text" placeholder="Location " name="location" class="location"/></br>
<input type="submit" value="Add Booking" />
</form>
Javascript is only needed here if you want to perform some sort of validation
NOTE
Avoid adding variables directly to your query, you will be vulnerable to SQL injection.
Here is what you can do:
$con = mysql_connect(".....",".....",".....");
$name = mysql_real_escape_string($_GET['name']);
$number = mysql_real_escape_string($_GET['number']);
$location = mysql_real_escape_string($_GET['location']);
create an , then set that when the button is clicked, the form is submitted. ie
but = document.getElementById('clickButton');
formToSubmit = document.getElementById('myForm');
but.onclick = function(){
formToSubmit.submit();
};
You don't need JavaScript to submit a form. It looks like you're just missing the < from <?php for now.
You could explicitly specify the action and method on the form HTML element, but if you don't it's a GET request and it will submit to the current URL (Web address).
Really, if you're doing something other than fetching data (like a search), your form should be using a HTTP POST, not a GET. For more understanding of why this kind of thing matters, see What should every programmer know about web development. However, that is a very big topic!
You just need to postback the form, in other words, set an action on the form as in:
<form id="mainForm" action="process.php" method="post">..
And add an onclick handler on the button as follows:
<input type="submit" value="Add Booking" onclick="javascript:document.getElementById('mainForm').submit();" />
However, not that I set the method to post; this will require your PHP code to change to:
$name = $_POST['name'];
$number = $_POST['number'];
$location = $_POST['location'];
Using POST in this case may not be necessary but you need to be aware that using GET will encode the form parameters in the URL as in process.php?name=value&numner=value... and some of this information may be sensitive and therefore, desirable to be submitted to the server in the body of the HTTP request as opposed to transmitted encoded in the URL.

PHP Uploading: Uploading multiple files?

I'm currently uploading a single file successfully with the following form:
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
And with the following script:
<?php
error_reporting(E_ALL);
if (($_FILES["file"]["size"] < 20000))
{
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 />";
$moved = move_uploaded_file($_FILES["file"]["tmp_name"], "C:/inetpub/wwwroot/PHP_Ramp/upload/" . $_FILES["file"]["name"]);
if ($moved) {
echo "Move: Success <br/>";
}
else {
echo "Move Failed <br/>";
}
echo "Stored in: " . "C:/inetpub/wwwroot/PHP_Ramp/upload/" . $_FILES["file"]["name"];
}
}
else
{
echo "Invalid file";
}
?>
I'm now trying to allow the user to select three different files from the form. I've found a few guides that show how to do something similar, but I can't quite get it working.
I've modified the form as follows (to include three inputs):
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="file" name="file" id="file" />
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
But I'm not sure how to modify the php to handle all three files. I know I need to iterate through _FILES but everything I've tried isn't working. Any pointers would be appreciated.
Each file element must have a unique name, or use PHP's array shorthand:
<input type="file" name="file1" />
<input type="file" name="file2" />
or
<input type="file" name="file[]" />
<input type="file" name="file[]" />
Remember - the name attribute defines how you'll identify that field on the server, and if you use the same name multiple times, PHP will overwrite previous copies with the latest one as it parses through the submitted data. The array notation ([]) tells PHP that you INTENDED to have multiple fields with the same name, and that each copy it finds should be added to an array, not overwritten.
For the unique name version, you'd handle each as you are right now with the single file.
For the array version, PHP has a design stupidity that requires slightly different handling. You end up with a $_FILES array that looks like
$_FILES = array(
'fieldname' => array(
'name' => array(
0 => 'first file',
1 => 'second file',
etc...
)
)
)
You need to change
<input name="file" />
to
<input name="file[]" />
To make them into an array.
Then in your script, you reference them as:
$_FILES['file']['name'][0]; // first file
$_FILES['file']['name'][1]; // second file
Note you can replace name with any of the other file properties that you usually would use on a single file (e.g. size, type etc).
Alternatively, you can give them all different names:
<input name="firstfile" />
<input name="secondfile" />
Then in your script:
$_FILES['firstfile']; // first file
$_FILES['secondfile']; // second file
You can select multiple file in single input like this..
<input type="file" name="pic[]" id="pic" accept="image/*" multiple="multiple"/>
This input box can accept multiple files by pressing control key. Now you can access them in php like this
$_FILES['file']['name'][0]; // first file
$_FILES['file']['name'][1]; // second file
KISS Code with some explanations:
There is fully functional simple code below to get you started. You can add error checking, max size stuff etc after you get something simple working.
The $_FILES array is a 3 dimensional array built into PHP, and that's where all the uploaded file info is stored.
There will only be ONE element for each 'name=' part of the HTML INPUT tag.
So if your INPUT tag looks like this:
<INPUT name="InpFile[]" type="file" />
The $_FILES array will have one top array element named 'InpFile'.
Also notice the [] after the InpFile.....that tells PHP that each time you use an input tag with that same 'name' it will add it to that same $_FILES array top element.
Within that one element there are 5 other array elements with the names: 'name', 'type', 'tmp_name', 'error', and 'size'.
And each one of those array elements will contain the data for each file that is uploaded.
Your first uploaded file name will be in $_FILES ['InpFile']['name']['0']
And the other info about your first uploaded file will also be in the array the same way, for example the size of the first file will be in $_FILES ['InpFile']['size']['0']
Each subsequent file name will be in $_FILES ['InpFile']['name'][1], $_FILES ['InpFile']['name'][2]....etc
After your upload, each file will have a random temporary name in the $_FILES ['InpFile']['tmp_name'][0...n] element, which is the name that it uses to first upload the files to a temporary area.
SO, after you upload, you have to move the files from the temporary area to where you want them.
That is done with this statement:
move_uploaded_file($_FILES['InpFile']['tmp_name'][$Key],
$_FILES['InpFile']['name'][$Key] )
or die("Move from Temp area failed");
In the foreach statement below, $Key and $Name are only there so that $Key will get assigned increasing numbers for each iteration...i.e. 0, 1, 2.....etc, and that you can then use $Key to reference the name, tmp_name, etc of each file in the array.
This code lets you do it all on one page, since the form actually calls itself (action="") to post. So the first time the page is loaded, you would get an error in the php code because $_FILES hasn't been set yet......so all the code is in an If statement: If ($_FILES).
After you submit the form, it will do it's thing and then echo a status for each file after it's been moved to your area.
Also, this code will upload the file to the same directory the page is in...you can change all that using info from other posts on SO.
<FORM action="" method="post" enctype="multipart/form-data">
<P align="center"><B>Choose Files</B><BR>
<BR>
File One:
<INPUT name="InpFile[]" type="file" />
<BR>
<BR>
File Two:
<INPUT name="InpFile[]" type="file" />
<BR>
</P>
<P align="center"><BR>
<INPUT type="submit" name="submit" value="UpLoad">
</P>
</FORM>
<H3 align="center"> </H3>
<H3 align="center">Status:</H3>
<P align="center"> </P>
<P align="center">
Put this PHP Code right here on the same page:
<?php
If ($_FILES) {
foreach ($_FILES ['InpFile']['name'] as $Key => $Name) {
move_uploaded_file(
$_FILES['InpFile']['tmp_name'][$Key],
$_FILES['InpFile']['name'][$Key]
) or die("Move from Temp area Failed");
$EFileName = $_FILES['InpFile']['name'][$Key];
echo "<P>$EFileName: Uploaded";
}
}
?>
You need to change the value of the name attribute in the HTML side to file[] and then in PHP just iterate through $_FILES['files'] and process each element as you normally would with a single file.

How to store file name in database, with other info while uploading image to server using PHP?

Hi I have read many forums and websites that tell you how to upload an image to a server and I have managed to get this working, I can upload a file to a my server but storing the file name does work on the following example I found and I also need to create a form that allows more data to be entered to the database. I am stuck with this as a have done much PHP before. I have come to the end of trying different websites tutorials with no much success could anyone please help me! I need it done for a project I'm doing.
I am basically trying to make a CMS that allows users to upload a photo of a band member and have information stored about them so that it can be displayed on a webpage for the public to view.
My Table looks like this:
Field Type Null Default
id int(10) No
nameMember varchar(25) No
bandMember text No
photo varchar(30) No
aboutMember text No
otherBands text No
The form I want will look like this:
<h1>Adding a new Band Member or Affiliate</h1>
<form method="post" action="addMember.php" enctype="multipart/form-data">
<p>
Please Enter the Band Members Name.
</p>
<p>
Band Member or Affiliates Name:
</p>
<input type="text" name="nameMember"/>
<p>
Please Enter the Band Members Position. Example:Drums.
</p>
<p>
Member's Position:
</p>
<input type="text" name="bandMember"/>
<p>
Please Upload a Photo in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten!
</p>
<p>
Photo:
</p>
<input type="file" name="filep" size=35 />
<p>
Please Enter any other information about the band member here.
</p>
<p>
Other Member Information:
</p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
<p>
Please Enter any other Bands the Member has been in.
</p>
<p>
Other Bands:
</p>
<input type="text" name="otherBands" size=30 />
<br/>
<br/>
<input TYPE="submit" title="Add data to the Database" value="Add Member"/>
</form>
The Example that uploads an Image to the server and only, that is this:
<?
if ($_POST["action"] == "Load")
{
$folder = "images/";
move_uploaded_file($_FILES["filep"]["tmp_name"] , "$folder".$_FILES["filep"]["name"]);
echo "
<p align=center>File ".$_FILES["filep"]["name"]."loaded...";
$result = mysql_connect("localhost", "******", "*****") or die ("Could not save image name
Error: " . mysql_error());
mysql_select_db("project") or die("Could not select database");
mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
if($result) { echo "Image name saved into database
"; }
}
?>
And the Examples form I have to use is this:
<form action=addMember.php method=post enctype="multipart/form-data">
<table border="0" cellspacing="0" align=center cellpadding="3" bordercolor="#cccccc">
<tr>
<td>File:</td>
<td><input type="file" name="filep" size=45></td>
</tr>
<tr>
<td colspan=2><p align=center>
<input type=submit name=action value="Load">
</td>
</tr>
</table>
</form>
PS: Images file is open for writing to.
Here is the answer for those of you looking like I did all over the web trying to find out how to do this task. Uploading a photo to a server with the file name stored in a mysql database and other form data you want in your Database. Please let me know if it helped.
Firstly the form you need:
<form method="post" action="addMember.php" enctype="multipart/form-data">
<p>
Please Enter the Band Members Name.
</p>
<p>
Band Member or Affiliates Name:
</p>
<input type="text" name="nameMember"/>
<p>
Please Enter the Band Members Position. Example:Drums.
</p>
<p>
Band Position:
</p>
<input type="text" name="bandMember"/>
<p>
Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
</p>
<p>
Photo:
</p>
<input type="hidden" name="size" value="350000">
<input type="file" name="photo">
<p>
Please Enter any other information about the band member here.
</p>
<p>
Other Member Information:
</p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
<p>
Please Enter any other Bands the Member has been in.
</p>
<p>
Other Bands:
</p>
<input type="text" name="otherBands" size=30 />
<br/>
<br/>
<input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
</form>
Then this code processes you data from the form:
<?php
// This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);
// This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];
// Connects to your Database
mysqli_connect("yourhost", "username", "password") or die(mysqli_error()) ;
mysqli_select_db("dbName") or die(mysqli_error()) ;
// Writes the information to the database
mysqli_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;
// Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
// Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
// Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
Code edited from www.about.com
<form method="post" action="addMember.php" enctype="multipart/form-data">
<p>
Please Enter the Band Members Name.
</p>
<p>
Band Member or Affiliates Name:
</p>
<input type="text" name="nameMember"/>
<p>
Please Enter the Band Members Position. Example:Drums.
</p>
<p>
Band Position:
</p>
<input type="text" name="bandMember"/>
<p>
Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
</p>
<p>
Photo:
</p>
<input type="hidden" name="size" value="350000">
<input type="file" name="photo">
<p>
Please Enter any other information about the band member here.
</p>
<p>
Other Member Information:
</p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
<p>
Please Enter any other Bands the Member has been in.
</p>
<p>
Other Bands:
</p>
<input type="text" name="otherBands" size=30 />
<br/>
<br/>
<input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
</form>
save it as addMember.php
<?php
//This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];
// Connects to your Database
mysql_connect("yourhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("dbName") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
in the above code one little bug ,i fixed that bug.
You have an ID for each photo so my suggestion is you rename the photo. For example you rename it by the date
<?php
$date = getdate();
$name .= $date[hours];
$name .= $date[minutes];
$name .= $date[seconds];
$name .= $date[year];
$name .= $date[mon];
$name .= $date[mday];
?>
note: don't forget the file extension of your file or you can generate random string for the photo, but I would not recommend that. I would also recommend you to check the file extension before you upload it to your directory.
<?php
if ((($_FILES["photo"]["type"] == "image/jpeg")
|| ($_FILES["photo"]["type"] == "image/pjpg"))
&& ($_FILES["photo"]["size"] < 100000000))
{
move_uploaded_file($_FILES["photo"]["tmp_name"], $target.$name);
if(mysql_query("your query"))
{
//success handling
}
else
{
//failed handling
}
}
else
{
//error handling
}
?>
Hope this might help.
Adding the following avoids problems with quotes in file names, e.g.
"freddy's pic.jpg"
which are acceptable on some operating systems.
Before:
$pic=($_FILES['photo']['name']);
After:
$pic=(mysql_real_escape_string($_FILES['photo']['name']));
If you want to input more data into the form, you simply access the submitted data through $_POST.
If you have
<input type="text" name="firstname" />
you access it with
$firstname = $_POST["firstname"];
You could then update your query line to read
mysql_query("INSERT INTO dbProfiles (photo,firstname)
VALUES('{$filename}','{$firstname}')");
Note: Always filter and sanitize your data.
Your part:
$result = mysql_connect("localhost", "******", "*****") or die ("Could not save image name
Error: " . mysql_error());
mysql_select_db("project") or die("Could not select database");
mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
if($result) { echo "Image name saved into database
";
Doesn't make much sense, your connection shouldn't be named $result but that is a naming issue not a coding one.
What is a coding issue is if($result), your saying if you can connect to the database regardless of the insert query failing or succeeding you will output "Image saved into database".
Try adding do
$realresult = mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
and change the if($result) to $realresult
I suspect your query is failing, perhaps you have additional columns or something?
Try copy/pasting your query, replacing the ".$_FILES['filep']['name']." with test and running it in your query browser and see if it goes in.

Categories