Hi everyone, am trying to save excel/docs filename in mysql and then display the filename and open the file to edit. The filename can be save in mysql but unable to display the filename and open the file. Appreciate if you could advise. Thanks a lot.

    <div id="tabs-1"> <?php
    error_reporting(E_ALL ^ E_NOTICE);
    $con = mysql_connect("localhost","user","");
    if (!$con){
    die("Can not connect: " . mysql_error());
    }
    mysql_select_db("pq",$con);

    $Picid = $_GET['Picid'];
    $nwQty = "SELECT * FROM progress WHERE Picid = '$Picid'";
    // check if the progress is already
    $solution = mysql_query($nwQty);
    if(isset($_POST['submit'])){
    if (mysql_num_rows($solution) == 0){
        // put the progress in table
    $sql = "INSERT INTO progress(Attachment1,Attachment11,
    Picid) VALUES ('" . $_POST["Attachment1"] . "','" . $_POST["Attachment11"] . "','" . $Picid . "')"; 
    $result = mysql_query($sql);
    } else {
        // update progress in table
    $sql =("UPDATE progress SET  Attachment1='" . $_POST["Attachment1"] . "',
    Attachment11='" . $_POST["Attachment11"] . "'    WHERE Picid='" . $Picid . "'");
    $result = mysql_query($sql);
    echo('Record Updated');
    }
    $result = mysql_query("SELECT * FROM progress WHERE  Picid='$Picid' ");
    $row= mysql_fetch_array($result); 
    }
    ?> <form name="progress" id="progress" method="post" action=""> <p><ENCTYPE="multipart/form-data">Forms: <input type="file" name="Attachment1" id="Attachment1" MAXLENGTH=50  ALLOW="text/*" value="<?php echo $row['Attachment1']; ?>"></p> <p><ENCTYPE="multipart/form-data">Department Forms: <input type="file" name="Attachment11" id="Attachment11" MAXLENGTH=50  ALLOW="text/*" value="<?php echo $row['Attachment11']; ?>"></p> <input type="hidden" name="Picid" id="Picid" value="<?php echo $row['Picid']; ?>" > <td colspan="2"><input type="submit" name="submit" id="submit" value="Save" class="btnSubmit"></td> <?php
    mysql_close($con);  
    ?> </div> </form>

Dani AI

Generated

Quick summary and a practical fix for the problems called out by and @Diafol: the form markup and enctype must be correct, you cannot prefill an <input type="file">, use prepared statements (PDO or mysqli) instead of mysql_*, and store a safe filename (not the raw server path) in the database. Below are concise, actionable steps and example code to get upload → DB → view working reliably.

  • Checklist (do these in order):
    1. Fix the form: <form method="post" enctype="multipart/form-data"> and close it properly. Do not set a value on the file input.
    2. Validate $_FILES['Attachment1']['error'] and check file_uploads, upload_max_filesize, post_max_size.
    3. Sanitize the original name, create a unique filename (timestamp or random hash), and move the uploaded file with move_uploaded_file.
    4. Store only the new filename (or a relative web path) in the DB using a prepared statement.
    5. To show the existing file, print a link and include a hidden input with the existing filename so it can be preserved if no new file is uploaded.

Example (upload + store with PDO, very small outline):

// handle upload (outline)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_FILES['Attachment1']) && $_FILES['Attachment1']['error'] === UPLOAD_ERR_OK) {
    $orig = $_FILES['Attachment1']['name'];
    $base = preg_replace('/[^A-Za-z0-9._-]/', '_', pathinfo($orig, PATHINFO_FILENAME));
    $ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
    $newName = $base . '_' . time() . '.' . $ext;
    $uploadDir = __DIR__ . '/upload/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
    if (move_uploaded_file($_FILES['Attachment1']['tmp_name'], $uploadDir . $newName)) {
        $pdo = new PDO('mysql:host=localhost;dbname=pq;charset=utf8mb4','user','pass', [PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
        $stmt = $pdo->prepare('INSERT INTO progress (Attachment1, Picid) VALUES (:f,:p)');
        $stmt->execute([':f'=>$newName, ':p'=>$_POST['Picid']]);
    }
}

Display (inside the form):

if (!empty($row['Attachment1'])) {
    echo '<a href="/upload/' . htmlspecialchars($row['Attachment1'], ENT_QUOTES) . '" target="_blank">View file</a>';
    echo '<input type="hidden" name="existing_Attachment1" value="' . htmlspecialchars($row['Attachment1'], ENT_QUOTES) . '">';
}

Troubleshooting tips: check $_FILES keys (your code used different names like myfile, file, Attachment1), inspect $_FILES['...']['error'] and is_uploaded_file() during debugging, avoid storing full server paths in the DB, and always validate MIME/type and extension before trusting a file. This approach preserves the existing filename for display (since file inputs can’t be prefilled) and keeps uploads secure and query-safe.

Recommended Answers

All 4 Replies

Member Avatar for Member #120589

1) Don't use deprecated code (mysql_* functions)
2) Avoid mixing PHP and HTML wherever possible. Only include echo / loops / conditionals if able. Bulk PHP shuld go above the DTD or in an include file.
3) You are wide open to SQL injections - THIS IS IMPT!!!
4) You are trying to programmatically put the filename into a file input. This can't be done.
5) The form tag looks messed up - form attributes (enctype) are placed as some sort of tag. Wrong. No close form tags. The HTML is a mess, start again.

Please read my tutorial ( DW Tutorial: Common Issues with MySQL and PHP ) on the use of PDO or mysqli. This code is downright dangerous.

Hi Diafol, thanks a lot for your advise. So for item 2), should i separate the php coding for file display and open in another file and the html in another file? Thanks.

Hi, i was able to save the file to server in folder14 using the coding below. Appreciate if you could advise how to display the file name in the form and view the file from the form. Thanks a lot.

            <?php
              if ( isset($_POST['myupload'])){

                if($_FILES['myfile']['size'] > 0){
                    $path = $_SERVER['DOCUMENT_ROOT']."\folder14";
                    $targetfolder = "\\upload\\"; 
                    $targetfolder = $path . $targetfolder . basename( $_FILES['myfile']['name']) ;          

                    $result = move_uploaded_file($_FILES["myfile"]["tmp_name"], $targetfolder);
                    if($result) {
                        echo "The file ". basename( $_FILES['file']['name']). " is uploaded<br>";
                    } else {
                        echo "Problem uploading file<br>";
                    } 
                }else{       
                    echo "Error on uploading file";
                }
            }
            ?>
             </table>
             <html>
             <head>
             <title>A simple example of uploading a file using PHP script</title>
             </head>
             <body>
             <b>Simple example of uploading a file</b><br/>
             Choose a file to be uploaded<br />
             <form action="upload.php" method="post" enctype="multipart/form-data">
             <input type="file" name="myfile" size="50" />
             <br />
             <input type="submit" name="myupload" value="Upload" />
             </form>
             </body>
             </html>

Hi, i am now able to upload,display and view the file with the coding below. However, i still cannot save the filename in mysql. Kindly please advise. Thanks a lot.

        <?php 
        $con = mysql_connect("localhost","user","");
        if (!$con){
        die("Can not connect: " . mysql_error());
        }
        mysql_select_db("pq",$con);

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

            if($_FILES['Attachment1']['size'] > 0){
                $path = $_SERVER['DOCUMENT_ROOT']."\folder14";
                $targetfolder = "\\upload\\"; 
                $targetfolder = $path . $targetfolder . basename( $_FILES['Attachment1']['name']) ;             

                $result = move_uploaded_file($_FILES["Attachment1"]["tmp_name"], $targetfolder);
                $sql="INSERT INTO progress(Attachment1) VALUES('$targetfolder')";
         mysql_query($sql); 

                if($result) {
                    echo "The file ". basename( $_FILES['file']['name']). " is uploaded<br>";

                } else {
                    echo "Problem uploading file<br>";
                } 
            }else{       
                echo "Error on uploading file";
            }
        }

        ?>
         </table>
         <html>
         <head>
         <title>A simple example of uploading a file using PHP script</title>
         </head>
         <body>
         <b>Simple example of uploading a file</b><br/>
         Choose a file to be uploaded<br />
         <form action="upload.php" method="post" enctype="multipart/form-data">
         <input type="file" name="Attachment1" size="50" />
         <br />
         <input type="submit" name="myupload" value="Upload" />
         </form>
         </body>
         </html>
         <?php
         $handle = opendir('upload');
        if($handle){
            while(($entry = readdir($handle)) !== false){
                if($entry != '.' && $entry != '..'){
                    echo "<a href=\"upload/$entry\">$entry</a><br>";
                }
            }
            closedir($handle);
        } 
        ?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.