Thread: Form entry

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2003
    Posts
    459
    Rep Power
    80

    Form entry


    Can someone look at this code and see what the problem is. It is not entering the data to the database. But I am not getting any errors.
    PHP Code:
    <?php 


    ini_set 
    ('display_errors'1);
    error_reporting (E_ALL & ~E_NOTICE);

    if (isset (
    $_POST['submit'])) 
    {
    if (
    $dbc mysql_connect
    ('localhost''root''xxxxxx')) 
    {
    if (!@
    mysql_select_db ('landings'))
    {
    die (
    '<p> Could not select database because: <b>' mysql_error() . '</b></p>');
    }
    } else {

    die (
    '<p> Could not connect to MySQL because: <b>' mysql_error() . '</b></p>');
    }
    $query "INSERT INTO property (ID, type, title, description, address, price, contact, phone, email) 
    VALUES (0,'
    {$_POST['type']}', '{$_POST['title']}','{$_POST['description']}','{$_POST['address']}','{$_POST['price']}','{$_POST['contact']}','{$_POST['phone']}','{$_POST['email']}')";

    if (@
    mysql_query ($query)) {
    print 
    '<p>Your entry has been posted. Thank you.</p>';
    } else {
    print 
    "<p>Could not add post because: <b>" mysql_error() . "</b> The  query was $query.</p>";
    }
    mysql_close();
    }
    ?>
    Code:
    <form action="enter_property.php" method="post">
    <p>Type: <input type="text" name="type" /></p>
    <p>Title:<input type="text" name="title" /></p>
    <p>Description:<input type="text" name="description" /></p>
    <p>Address:<input type="text" name="address" /></p>
    <p>Price:<input type="text" name="price" /></p>
    <p>Contact:<input type="text" name="contact" /></p>
    <p>Phone:<input type="text" name="phone"/></p>
    <p>Email:<input type="text" name="email" /></p>
    <input type="submit" name="button" value="Submit" />
    </form>
    </body>
    </html>
  2. #2
  3. Headless Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,931
    Rep Power
    9647
    Do a echo($query); just before you do the query itself, and make sure it looks like it should.
    And if you want to look for error messages you should to remove the @s you have - those will deliberately hide any messages.

    Also your script is vulnerable to SQL injections and that's a very bad thing. The two green links in my sig: check them out.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2003
    Posts
    459
    Rep Power
    80
    I got it to work. I was getting blank entries because I had $POST instead of $_POST

    Comments on this post

    • bigSeth agrees : I've done that...
    Last edited by mallen; September 17th, 2007 at 05:32 AM.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2003
    Posts
    459
    Rep Power
    80
    Requinix, That tip using the query really worked great. Now I have a new challenge. I have one form that can enter text into the database. I also have a form that can upload a image and change its name.

    Now I want to put both forms together. I know it has something to do with the $query = "INSERT INTO line.

    [PHP]<?php

    define ("MAX_SIZE","100");

    function getExtension($str) {
    $i = strrpos($str,".");
    if (!$i) { return ""; }
    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);
    return $ext;
    }

    $errors=0;

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

    $image=$_FILES['image']['name'];

    if ($image)
    {

    $filename = stripslashes($_FILES['image']['name']);
    $extension = getExtension($filename);
    $extension = strtolower($extension);

    if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
    {
    echo '<h1>Unknown extension!</h1>';
    $errors=1;
    }
    else
    {

    $size=filesize($_FILES['image']['tmp_name']);

    if ($size > MAX_SIZE*1024)
    {
    echo '<h1>You have exceeded the size limit!</h1>';
    $errors=1;
    }

    $image_name=time().'.'.$extension;

    $newname="uploads/images/".$image_name;

    $copied = copy($_FILES['image']['tmp_name'], $newname);
    if (!$copied)
    {
    // Connect and select.
    if ($dbc = @mysql_connect ('localhost', 'root', 'xxxxxx)) {

    if (!mysql_select_db ('landings')) {
    die ('<p>Could not select the database because: <b>' . mysql_error() . '</b></p>');
    }

    } else {
    die ('<p>Could not connect to MySQL because: <b>' . mysql_error() . '</b></p>');
    }
    $query = "INSERT INTO property (ID, title, description, images, address, price, contact, phone, email) VALUES (0,'{$_POST['title']}', '{$_POST ['description']}','{$_POST ['images']}', '{$_POST ['address']}', '{$_POST ['price']}', '{$_POST ['contact']}', '{$_POST ['phone']}', '{$_POST ['email']}')";
    echo($query);

    echo '<h1>Copy unsuccessfull!</h1>';
    $errors=1;
    }}}}

    if(isset($_POST['Submit']) && !$errors)
    {
    echo "<h1>File Uploaded Successfully!</h1>";
    }

    ?>
    PHP Code:

     
    [CODE]<!--next comes the formyou must set the enctype to "multipart/frm-data" and use an input type "file" -->
     <
    form name="newad" method="post" enctype="multipart/form-data"  action="enter_property.php">[/CODE
    Code:
     <table>
     	<tr><td><input type="text" name="title">
     	Title</td>
     	</tr>
     	<tr><td><input type="text" name="description">
     	Description</td>
     	</tr>
        <tr><td><input type="file" name="image"></td></tr>
       <tr><td><input type="text" name="address">
       Address</td>
       </tr>
        <tr><td><input type="text" name="price">
        Price</td>
        </tr>
        <tr><td><input type="text" name="contact">
        Contact</td>
        </tr>
        <tr><td><input type="text" name="phone">
        Phone</td>
        </tr>
        <tr><td><input type="text" name="email">
        Email</td>
        </tr>
     </table>
     <input name="Submit" type="submit" value="Upload image" id="Submit" />	
    </form>
    </body>
    </html>
    Last edited by mallen; September 18th, 2007 at 08:12 PM. Reason: enter data and image
  8. #5
  9. Headless Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,931
    Rep Power
    9647
    Looking only at the query there, you need to use the new name of the image, not the original name (which is actually one of the elements in the $_FILES['image'] array, not in $_POST). Depending on what you're storing, $newname looks to be the full path of the image, and $image_name is just the filename.

    And also use move_uploaded_file instead of copy - the whole point of that function is to deal with uploaded files anyways.

    By the way, you're missing a ' on your mysql_connect line.
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2003
    Posts
    459
    Rep Power
    80
    I forgot the ' on my mysql but its in there. Its uploading the image and changing its name. So part of the form is working. Its just not entering the ID, description, etc in the database.

    Would this be causing the whole query not to work? I am not getting any error messages. '{$_POST ['images']}' I would think it would display an error.
  12. #7
  13. Headless Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,931
    Rep Power
    9647
    It should raise an error, yes, but you removed the error_reporting line
    $_POST["images"] will be an error (undefined offset "images"), and would insert nothing into the query, so then the query would look like
    Code:
    title, description, , address...
    and those two commas would cause the query to fail, so nothing gets updated.
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2003
    Posts
    459
    Rep Power
    80
    Ok I'm getting closer. The form is now entering all the data correctly. It is also uploading the file and changing its name.

    But the only thing is I want it to store the image name such as 34245522662.gif in the images table.

    I am getting this error: Notice: Undefined index: images
    I think '{$_POST ['images']}' is the problem. And the newname.

    [php]
    <?php

    /
    define ("MAX_SIZE","100");

    function getExtension($str) {
    $i = strrpos($str,".");
    if (!$i) { return ""; }
    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);
    return $ext;
    }


    $errors=0;
    //checks if the form has been submitted
    if(isset($_POST['Submit']))
    {


    $image=$_FILES['image']['name'];
    //if it is not empty
    if ($image)
    {

    $filename = stripslashes($_FILES['image']['name']);

    $extension = getExtension($filename);
    $extension = strtolower($extension);

    if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
    {

    echo '<h1>Unknown extension!</h1>';
    $errors=1;
    }
    else

    if ($dbc = @mysql_connect ('localhost', 'root', 'XXXX')) {

    if (!mysql_select_db ('landings')) {
    die ('<p>Could not select the database because: <b>' . mysql_error() . '</b></p>');
    }

    } else {
    die ('<p>Could not connect to MySQL because: <b>' . mysql_error() . '</b></p>');
    }

    $query = "INSERT INTO property (ID, title, description, images, address, price, contact, phone, email) VALUES (0,'{$_POST['title']}', '{$_POST ['description']}','{$_POST ['images']}', '{$_POST ['address']}', '{$_POST ['price']}', '{$_POST ['contact']}', '{$_POST ['phone']}', '{$_POST ['email']}')";
    echo($query);
    // Execute the query.
    if (mysql_query ($query)) {
    print '<p>Your propERTY entry has been added.</p>';
    } else {
    print "<p>Could not add the entry because: <b>" . mysql_error() . "</b>. The query was $query.</p>";
    }

    mysql_close();

    } {



    $size=filesize($_FILES['image']['tmp_name']);


    if ($size > MAX_SIZE*1024)
    {
    echo '<h1>You have exceeded the size limit!</h1>';
    $errors=1;
    }

    $image_name=time().'.'.$extension;

    $newname="uploads/images/".$image_name;

    $copied = copy($_FILES['image']['tmp_name'], $newname);
    if (!$copied)
    {
    echo '<h1>Copy unsuccessfull!</h1>';
    $errors=1;
    }}}


    if(isset($_POST['Submit']) && !$errors)
    {
    echo "<h1>File Uploaded Successfully! Try again!</h1>";
    }

    ?>[PHP]
  16. #9
  17. Headless Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,931
    Rep Power
    9647
    Right, that is the problem.

    See how everywhere else there's a $_FILES["image"]? That's because when you upload a file the information about it goes into the $_FILES array and not into $_POST. So what you would be using is $_FILES instead.

    But ignore that for the moment. Take a look at the order in which your script does things: it checks that the form was submitted, inserts the stuff into the database table, and tells the user everything was okay. Then it starts working on the image, moving it around and all that.
    If someone uploads an image that's too big, they'll get a "property added" message then a "file too big" notice. So does that mean the property was added but without the picture? Doesn't make sense.

    So here's what you do. You move all that stuff about dealing with the file inside of the bit that inserts the data in the database. That way if the image is too big, you won't have to do the insert query and everything will make sense again.
    And there's a nice benefit to that too - that bit you just moved also has a variable holding the new name of the image: $image_name. You can then use that in your query.

    PHP Code:
    <?php

    define 
    ("MAX_SIZE","100"); 

    function 
    getExtension($str) {
    $i strrpos($str,".");
    if (!
    $i) { return ""; }
    $l strlen($str) - $i;
    $ext substr($str,$i+1,$l);
    return 
    $ext;
    }


    $errors=0;
    //checks if the form has been submitted
    if(isset($_POST['Submit'])) 
    {


    $image=$_FILES['image']['name'];
    //if it is not empty
    if ($image
    {

    $filename stripslashes($_FILES['image']['name']);

    $extension getExtension($filename);
    $extension strtolower($extension);

    if ((
    $extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
    {

    echo 
    '<h1>Unknown extension!</h1>';
    $errors=1;
    }
    else

    if (
    $dbc = @mysql_connect ('localhost''root''XXXX')) {

    if (!
    mysql_select_db ('landings')) {
    die (
    '<p>Could not select the database because: <b>' mysql_error() . '</b></p>');
    }

    } else {
    die (
    '<p>Could not connect to MySQL because: <b>' mysql_error() . '</b></p>');
    }

    $size=filesize($_FILES['image']['tmp_name']);

    if (
    $size MAX_SIZE*1024)
    {
    echo 
    '<h1>You have exceeded the size limit!</h1>';
    $errors=1;
    }

    $image_name=time().'.'.$extension;

    $newname="uploads/images/".$image_name;

    $copied copy($_FILES['image']['tmp_name'], $newname);
    if (!
    $copied
    {
    echo 
    '<h1>Copy unsuccessfull!</h1>';
    $errors=1;
    }

    $query "INSERT INTO property (ID, title, description, images, address, price, contact, phone, email) VALUES (0,'{$_POST['title']}', '{$_POST ['description']}','{$image_name}', '{$_POST ['address']}', '{$_POST ['price']}', '{$_POST ['contact']}', '{$_POST ['phone']}', '{$_POST ['email']}')";
    echo(
    $query);
    // Execute the query.
    if (mysql_query ($query)) {
    print 
    '<p>Your propERTY entry has been added.</p>';
    } else {
    print 
    "<p>Could not add the entry because: <b>" mysql_error() . "</b>. The query was $query.</p>";
    }

    mysql_close();

    } {



    }}


    if(isset(
    $_POST['Submit']) && !$errors
    {
    echo 
    "<h1>File Uploaded Successfully! Try again!</h1>";
    }

    ?>
    See? I just moved that entire block somewhere into one of your ifs, and then stuck the $image_name into the query.

    Unfortunately you aren't done yet. There are a few syntax errors here and there: for example, you have an else that's missing the { after it. And there's an empty { } which I believe PHP will complain about. Go through the code as it is and make sure that everything reads correctly.
    And a suggestion: use indenting. It makes it easier to spot errors like those two I mentioned. Plus, it's just plain easier to read.
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2003
    Posts
    459
    Rep Power
    80
    Ok I fixed some of the code and got it working. Uploads all data to the database, uploads the image, changes its name and also stores the name of the file in the images column.

    Also if the file is the wrong type it displays the correct warning and does not upload the file. If it exceeds the max size it also displays a warning and does not upload the file. I have two more things I need to fix.

    1. I put die(); after the error so it would not upload the file. Is this ok?

    2. Is there a way to display the form again when it displays the error? Or maybe refresh the page?

    <?php
    if ($dbc = @mysql_connect ('localhost', 'root', 'xxxx)) {

    if (!mysql_select_db ('landings')) {
    die ('<p>Could not select the database because: <b>' . mysql_error() . '</b></p>');
    }

    } else {
    die ('<p>Could not connect to MySQL because: <b>' . mysql_error() . '</b></p>');
    }
    define ("MAX_SIZE","100");

    function getExtension($str) {
    $i = strrpos($str,".");
    if (!$i) { return ""; }
    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);
    return $ext;
    }


    $errors=0;
    //checks if the form has been submitted
    if(isset($_POST['Submit']))
    {


    $image=$_FILES['image']['name'];
    //if it is not empty
    if ($image)
    {

    $filename = stripslashes($_FILES['image']['name']);

    $extension = getExtension($filename);
    $extension = strtolower($extension);

    if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
    {

    echo '<h3>Unknown extension! Only .gif, .jpg, and .png files are allowed to be uploaded </a>.</h3>';
    $errors=1;
    die ();

    }

    $size=filesize($_FILES['image']['tmp_name']);

    if ($size > MAX_SIZE*1024)
    {
    echo '<h1>You have exceeded the size limit!</h1>';
    $errors=1;
    die ();
    }

    $image_name=time().'.'.$extension;

    $newname="uploads/images/".$image_name;

    $copied = copy($_FILES['image']['tmp_name'], $newname);
    if (!$copied)
    {
    echo '<h1>Copy unsuccessfull!</h1>';
    $errors=1;
    }

    $query = "INSERT INTO property (ID, title, description, images, address, price, contact, phone, email) VALUES (0,'{$_POST['title']}', '{$_POST ['description']}','{$image_name}', '{$_POST ['address']}', '{$_POST ['price']}', '{$_POST ['contact']}', '{$_POST ['phone']}', '{$_POST ['email']}')";
    echo($query);
    // Execute the query.
    if (mysql_query ($query)) {
    print '<p>Your property entry has been added.</p>';
    } else {
    print "<p>Could not add the entry because: <b>" . mysql_error() . "</b>. The query was $query.</p>";
    }

    mysql_close();

    }
    }


    if(isset($_POST['Submit']) && !$errors)
    {
    echo "<h1>File Uploaded Successfully.</h1>";
    }

    ?>
    Form below....
  20. #11
  21. Web Developer/Musician
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Nov 2004
    Location
    Tennessee Mountains
    Posts
    2,424
    Rep Power
    1036
    Die() is okay for testing but not so good for production. That function stops all output including any further output of HTML. This is an ugly and user-unfriendly way to handle errors.

    Also, I'm glad you are working through the problems in your script, but you have gone through and written as well as altered quite a few lines of code. All without dealing with one of the issues already mentioned which is the most important of all. That is, not putting input from outside your script directly into SQL queries. Any input that is supposed to be a string in the query must be escaped with mysql_real_escape_string and anything that is to be a number, should be force cast to be so. Don't make the script public before you do that. I am a big believer in doing this sort of thing right up front, rather than doing double work after a script is working, to add security.
    Coder Central Tutorials, news and information for the programming community at large.
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2003
    Posts
    459
    Rep Power
    80
    Hammer65, What would you recommend to use other than die() ? If I don't include that, it will upload the file after it displays the error.

    Also can you point out what you mean by "not putting input from outside your script directly into SQL queries. Any input that is supposed to be a string in the query must be escaped with mysql_real_escape_string and anything that is to be a number, should be force cast to be so."

    I am testing for the file type and size. What exactly is the threat I should be concerned about?
    Last edited by mallen; September 21st, 2007 at 05:18 PM.
  24. #13
  25. Web Developer/Musician
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Nov 2004
    Location
    Tennessee Mountains
    Posts
    2,424
    Rep Power
    1036
    Handle the error with a proper display and a chance to go back to the form and try again. Restructure the code so that if there is an error you can redirect to the form with a friendly error message.

    What I mean by putting input values into SQL queries is don't do something like this...

    PHP Code:
    $sql 'INSERT INTO registration (id,name,address) values ($_POST['id'],$_POST['name'],$_POST['address'])'
    Someone can inject their own SQL into that via your submission page. Nothing from POST, GET or FILE for that matter should be input directly into a query without running it through an escape function. In the case of MySQL the function is mysql_real_escape_string().

    PHP Code:
    $name mysql_real_escape_string($_POST['name']);
    $address mysql_real_escape_string($_POST['address']);
    $id intval($_POST['id']);
    $sql 'INSERT INTO registration (id,name,address) values ($id,$name,$address)'
    Google for "SQL injection" for more information. It's a very dangerous security exploit. Any site that is publicly posted should have protection against it.
    Coder Central Tutorials, news and information for the programming community at large.

IMN logo majestic logo threadwatch logo seochat tools logo