By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,742 Members | 1,570 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,742 IT Pros & Developers. It's quick & easy.

PHP Data insert and image upload

P: 12
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_string(trim($_POST['name']));
$address = mysql_escape_string(trim($_POST['address']));
$postcode = mysql_escape_string(trim($_POST['postcode']));
$telephone = mysql_escape_string(trim($_POST['telephone']));
$email = mysql_escape_string(trim($_POST['email']));
$picture = mysql_escape_string(trim($_POST['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',$dbid)
or die ("Cannot find database");

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

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

<html>
<head>
<title>Data submission - db version</title>
</head>
<body>
<form enctype="multipart/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
Share this Question
Share on Google+
8 Replies


code green
Expert 100+
P: 1,726
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
Expert 2.5K+
P: 4,258
How do you know you have uploaded the image file? I'll bet you it is not uploaded.

Ronald :cool:
Mar 27 '07 #3

P: 12
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
Expert 100+
P: 1,726
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

P: 12
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
Expert 100+
P: 1,726
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_escape_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_escape_string($name);
//etc
//Then load the data into database
}
else
{
echo $msg;
//Reload the page
}[/PHP]
Mar 30 '07 #7

P: 12
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
Expert 100+
P: 1,726
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">Name:</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">Address:</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

Post your reply

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