473,770 Members | 2,004 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PHP Data insert and image upload

12 New Member
Hi i was wondering if anyone could help.... I have made a little script that puts whatever a user enters into a mysql database. As well as the forms my script has an image input that uploads an image to my webserver. The thing i'm stuck on is getting the script to input the name of the file into a field in the database.

So basically the file will be uploaded and when the submit button is clicked a link to that image will be generated and put into the database.

I've put my code below, i'm guessing i need a variable that will take the name of the file and add it to a pre defined url for example http://www.mysite.com/images/$file_name, then insert that along with everything else when i run the insert query? Also, how would i go about converting the filename into something radomly generated? So that it would stop any existing files being overwritten?


[PHP]<?php

if (isset($_POST['submitted'])) {

$name = mysql_escape_st ring(trim($_POS T['name']));
$address = mysql_escape_st ring(trim($_POS T['address']));
$postcode = mysql_escape_st ring(trim($_POS T['postcode']));
$telephone = mysql_escape_st ring(trim($_POS T['telephone']));
$email = mysql_escape_st ring(trim($_POS T['email']));
$picture = mysql_escape_st ring(trim($_POS T['picture']));

// This bit puts the file in the $file variable into the folder on the server.
if ($file_name !="") {
copy ("$file", "/var/www/vhosts/server.com/httpdocs/uploader1/$file_name")
or die ("Sorry there was a problem");}

$dbid = mysql_connect ('localhost', 'address', 'pass');
mysql_select_db ('addresses',$d bid)
or die ("Cannot find database");

$query = "INSERT INTO `book` (`aid`, `name`, `address`, `postcode`, `telephone`, `email`) VALUES ('', '$name', '$address', '$postcode', $telephone, '$email')";
$result = mysql_query($qu ery,$dbid)
or die("INSERT error:".mysql_e rror());

echo 'Row inserted and image uploaded';
exit;
}
?>

<html>
<head>
<title>Data submission - db version</title>
</head>
<body>
<form enctype="multip art/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name: <input name="name" /><br />
Address: <input name="address" /><br />
Postcode: <input name="postcode" /><br />
Telephone: <input name="telephone " /><br />
Email: <input name="email" /><br />
Select Picture: <input type="file" name="file" size"80"><br />
<br /><input type="submit" name="submitted " value="Submit" >
</form><br />
</body>
</html> [/PHP]
Mar 26 '07 #1
8 4028
code green
1,726 Recognized Expert Top Contributor
i'm guessing i need a variable that will take the name of the file and add it to a pre defined url for example http://www.mysite.com/images/$file_name
Your guess is correct but I cannot see the code that attempts your guess Please define your exact problem.
Mar 27 '07 #2
ronverdonk
4,258 Recognized Expert Specialist
How do you know you have uploaded the image file? I'll bet you it is not uploaded.

Ronald :cool:
Mar 27 '07 #3
andrewtayloruk
12 New Member
How do you know you have uploaded the image file? I'll bet you it is not uploaded.

Ronald :cool:
The file is uploading actually and i've got it to generate a random name during upload using uniqid(). I then put both variables $mysite = www.mysite.com and $file_name into the insert query. It's working but it seems a pretty dirty way of doing it.

I'm now stuck on displaying an error message and stopping the whole script whenever an invalid bit of data is put into one of the input boxes.

I've written a REGEX that will tell you to enter a valid email but it's just getting that to display next to the input box.

I'm guessing i need to look into boolean variables to get that working how i like??
Mar 28 '07 #4
code green
1,726 Recognized Expert Top Contributor
I'm now stuck on displaying an error message and stopping the whole script whenever an invalid bit of data is put into one of the input boxes.
This is very easy to solve. What is not easy is following your train of thought. Please define a problem and publish the relevant code for that problem.
Mar 28 '07 #5
andrewtayloruk
12 New Member
Hi, sorry i should have made myself clearer.

I've posted my code below, so far it's working, well it's uploading the file, renaming it and inserting the data from the form into the database. The problem i'm having is getting the script to stop if correct data is not entered into the form. Also, i'd like to get an error message to appear next to the relevant text boxes when incorrect information isn't entered. I'm aware this code isn't complete by the way so am not expecting it to work but i don't know where to go from here. Thanks

Expand|Select|Wrap|Line Numbers
  1. <?php 
  2.  
  3. if (isset($_POST['submitted'])) {
  4.  
  5.   $name = mysql_escape_string(trim($_POST['name']));
  6.   $address = mysql_escape_string(trim($_POST['address']));
  7.   $postcode = mysql_escape_string(trim($_POST['postcode']));
  8.   $telephone = mysql_escape_string(trim($_POST['telephone']));
  9.   $fixedemail = mysql_escape_string(trim($_POST['email']));
  10.   $imglocation = mysql_escape_string('http://www.mysitecom/uploader1/images/');
  11.  
  12.  
  13.   // This bit of code checks the form for correctly entered information
  14.   if (eregi('^([-a-z0-9._]+)@([-a-z0.9_]+\.+[a-z]{2,6})$',$fixedemail,$email))
  15.             { print "" ;}
  16.     else     { print "You entered an invalid email address. Please enter username@domain <br />" ; }        
  17.  
  18.  
  19.  
  20.       // This bit puts the file in the $file variable into the folder on the server and changes its name so it isn't overwritten
  21.          $file_name = uniqid("img").".jpg";
  22.  
  23.           if ($file_name !="") {
  24.             copy ("$file", "/var/www/vhosts/mysite.com/httpdocs/uploader1/images/$file_name")
  25.               or die ("Sorry there was a problem");}
  26.  
  27.  
  28.       // This is the SQL part of the code
  29.       $dbid = mysql_connect ('localhost', 'address', 'password');
  30.               mysql_select_db('addresses',$dbid) 
  31.               or die ("Cannot find database");
  32.  
  33.       $query = "INSERT INTO `book` (`aid`, `name`, `address`, `postcode`, `telephone`, `email`, `picture`) VALUES ('', '$name', '$address', '$postcode', '$telephone', '$email', '$imglocation$file_name')";
  34.       $result = mysql_query($query,$dbid) 
  35.        or die("INSERT error:".mysql_error());
  36.  
  37.       echo 'Row inserted and image uploaded';
  38.       exit;
  39. }
  40. ?>
  41.  
  42. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
  43.  
  44. <html>
  45. <head>
  46. <title>Data submission - db version</title>
  47. </head>
  48. <body>
  49. <form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  50. <table width="300">
  51. <tr><td width="50" align="left">Name:</td><td width="150" align="center"><input type="text" name="name"></td></tr>
  52. <tr><td width="50" align="left">Address:</td><td width="150" align="center"><input type="text" name="address"></td></tr>
  53. <tr><td width="50" align="left">Postcode:</td><td width="150" align="center"><input type="text" name="postcode"></td></tr>
  54. <tr><td width="50" align="left">Telephone:</td><td width="150" align="center"><input type="text" name="telephone"></td></tr>
  55. <tr><td width="50" align="left">Email:</td><td width="150" align="center"><input type="text" name="email"></td></tr>
  56. <tr><td width="80" align="left">Image:<br></td><td width="220" align="center" valign="middle"><input type="file" name="file"><br></td></tr>
  57. <tr><td align="left"><input type="submit" name="submitted" value="Submit" ></td></tr>
  58.  
  59. </table>
  60. </form>
  61. </body>
  62. </html>
Mar 30 '07 #6
code green
1,726 Recognized Expert Top Contributor
Check your data input after this point
Expand|Select|Wrap|Line Numbers
  1. if (isset($_POST['submitted'])) {
The following lines of code prepare the data for database input but no checking has been done prior. So forget about these for now
Expand|Select|Wrap|Line Numbers
  1.  $name = mysql_escape_string(trim($_POST['name']));
There are various ways of handling this - simple to sophisticated. A simple method is to create a valid form flag and a message string.[PHP]$valid = TRUE;
$msg = 'There were the following errors';[/PHP]
Then change your mysql_real_esca pe_string lines to
[PHP]$name = striptags(trim( $_POST['name']));
if(empty($name) ){
$valid = FALSE;
$msg = 'Please enter a name';
}[/PHP]And similar for the other fields.
A useful test for example could be
[PHP]if(!is_numeric( $telephone)){
$valid = FALSE;
$msg = 'Please enter a valid telephone number';
}[/PHP]When all input data has been tested simply test $valid
[PHP]if($valid){
$name = mysql_real_esca pe_string($name );
//etc
//Then load the data into database
}
else
{
echo $msg;
//Reload the page
}[/PHP]
Mar 30 '07 #7
andrewtayloruk
12 New Member
Hi, could you explain the more complicated ways of doing it? I've got it working how you suggested but it's not really what i'm after. It's printing the error messages but isn't showing them next to the input fields. Is it possible to get it to do this using the method you described?

Thanks for your help by the way.
Apr 2 '07 #8
code green
1,726 Recognized Expert Top Contributor
I made a slight error in my syntax. The $msg string should have been concatenated so as to print a list of errors ie.[PHP]$msg .= '<br>Please enter a name';[/PHP]
Hi, could you explain the more complicated ways
I was only referring to a form handling class or javascript here.
It's printing the error messages but isn't showing them next to the input fields.
If you want to do this the messages need seperating. I would collect them into an array instead of concatenating a string and name the element key the same as the relevant textbox name [PHP]$msg['name'] = 'Please enter your name';
$msg['postcode'] = 'Please enter a valid postcode';
//etc [/PHP] Then mix a bit of php into the html when creating your textboxes.
[PHP] <tr><td width="50" align="left">Na me:</td>
<td width="150" align="center"> <input type="text" name="name">
<?php if(isset($msg['name'])) echo $msg['name'];?> </td></tr>
<tr><td width="50" align="left">Ad dress:</td>
<td width="150" align="center"> <input type="text" name="address">
<?php if(isset($msg['address'])) echo $msg['address'];?> </td></tr>[/PHP] Good Luck
Apr 2 '07 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

15
12018
by: lawrence | last post by:
I've been using the following function (yes, it is inelegant, what can I say, I wrote it a long time ago) to upload images. Haven't had a problem with it for at least a year, and I don't recall changing it anytime recently. Nevertheless, the script is suddenly dying on this line: if (copy($uploadedFile, $pathToImageFolder)){ This is the error I get:
4
2457
by: DH | last post by:
I have a "file upload form" that works OK, but I have been unsuccessful in my attempt to also resize the uploaded .JPG (if it is too wide), over-writing the original .JPG, and then create and save a thumbnail.jpg .... all at the same time. Links to a working example would be appreciated. Thanks.
0
2382
by: Paul Hamlington | last post by:
Hello, I've been programming in ASP for a little while now and quite an advanced user, but I have come across an unusual problem in which I need assistance. I have built my own image upload, I have two versions of the binary to string conversion one fast, one slow because some servers use chillisoft and therefore the append function in not accessible for a disconnected recordset.
1
2278
pritipshah
by: pritipshah | last post by:
Hi All, I am using vtiger open source CRM and in that they are using FCKeditor for Image Upload (Resource browser window) but it is not upload or make new folder for image. Vtiger CRM fource to use IE for better performence so from the first day i was using IE7 for editing and testing. After some time today i tried it with Mozilla browser and Image upload works great in this browser, and sudanly i found that Image upload is not...
7
17058
by: mishrarajesh44 | last post by:
hii all Truly telling i hav got this code from net & i am finding error while running the code below.. code:- <?php $idir = "photo/"; // Path To Images Directory $tdir = "photo/thumbs/"; // Path To Thumbnails Directory $twidth = "125"; // Maximum Width For Thumbnail Images
3
1727
by: mishrarajesh44 | last post by:
hiiii, i am making addressbook, which will include name,mobile,address, photo, and want to save in mysql databqse all data and only the name of image file. i want that by clicking the submit buttton the data will be added to mysql database and image will b uploaded simulataneously, i know the code for both image upload & dataadding in mysql....and i need all them to b in one page.. But how to merge both, please ...
7
3733
by: dragiton | last post by:
SA Upload SQL Database variable types (image upload and storage) I am having trouble with the SA Upload utility. The following code used to work correctly. However, I lost my database and had to rebuild. Does anyone have any suggestions on what I may have wrong. I am not sure if I built my table to store the picture id's correctly. Maybe a field type or something. <form name="UpdatePropertyPicture" method="POST"...
1
4884
by: chennaibala | last post by:
can any one send me mutiple image upload program and save the file name with extension in mysql table.we must cheak uploaded file type like bmp or any image file while uploading. i develop program,which can upload many file in folder.problem is,am unable to save my file name in to database.because i used same name for all input file type as file. i dont know get name of file.below i presented my coding for ur view.fed up with my coding..pls...
1
4455
by: kimsengora | last post by:
Ex. I need to fill in values argument Field1 is text Field2 is image Insert into tbl1 values("'+val1+"','+val2+'") val2 is image like 0x424DFE9D00000000000036000000..................................... I really stuck on this with image values because I have to BCP out my data and and generate the insert statement with value data like above back to database
3
3120
by: Napsterr | last post by:
I have a RichTextEditor control. I want to insert image whereever the cursor is. Onclicking Insert link i want to insert Image. Is it possible? I have this design in .aspx page. After clicking on lnkBtnInsert, I want to insert Image which user have uploaded using fileupload control. <table border="0" cellpadding="0" cellspacing="0"> <tr> <td>
0
9618
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10101
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9906
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8933
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7456
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2849
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.