0

I am trying to upload txt file in database and also save it in file that been declare

  1. I include my file for your references
  2. I have tried like this if (isset($filename)) but it did not work
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>TRY</title>
        <link href="css/bootstrap.min.css" rel="stylesheet">
        <link href="css/font-awesome.min.css" rel="stylesheet">
        <link href="css/datepicker3.css" rel="stylesheet">
        <link href="css/styles.css" rel="stylesheet">

        <link rel="stylesheet" href="https://cdn.datatables.net/1.10.25/css/dataTables.bootstrap4.min.css">
        <link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.6.5/css/buttons.dataTables.min.css">
        <link rel="stylesheet" href="https://cdn.datatables.net/select/1.3.1/css/select.dataTables.min.css">
        <link rel="stylesheet" href="http://localhost/test/plugins/toastr/toastr.min.css">
        <style>
            select.error, textarea.error, input.error, label.error {
                color:#FF0000;
            }
        </style>
        
        <!--Custom Font-->
        <link href="https://fonts.googleapis.com/css?family=Montserrat:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">
        <!--[if lt IE 9]>
        <script src="js/html5shiv.js"></script>
        <script src="js/respond.min.js"></script>
        <![endif]-->
    </head>
    <body>
        <!-- Header -->
        <?php include('includes/header.php');?>
            
        <div class="col-sm-9 col-sm-offset-3 col-lg-10 col-lg-offset-2 main">

                    
                <div class="col-lg-12">
                    <div class="row" >
                        <div class="panel panel-default">
                            <div class="panel-heading">
                                UPLOAD FILE
                            </div>
                            
                            <div class="panel-body">
                                <table class="table table-bordered text-nowrap" width="100%" cellspacing="0" id="table_ex">
                                    <thead>
                                        <tr>
                                            <th>Id</th>
                                            <th>Username</th>
                                            <th>Title </th>
                                        </tr>
                                    </thead>
                                </table>
                            </div>
                        </div>                   
                    </div>
                </div>
            <!-- Modal Add -->
            <div id="ModalAdd" class="modal fade" role="dialog" data-backdrop="static" data-keyboard="false">
                <div class="modal-dialog">

                    <!-- Modal content-->
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                            <h4 class="modal-title">Create New Sequences</h4>
                        </div>
                        <form id="formadd" method="post" enctype="multipart/form-data">
                            <div class="modal-body">
                                <div class="form-group">
                                    <label>Username</label>
                                    <input type="text" name="username">
                                </div>
                                <div class="form-group">
                                    <label>UploadImage</label>
                                    <input type="file" name='myfile'>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-primary" id="BtnAdd" value="Upload">Create</button>
                                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Footer -->
        <?php include('includes/footer.php');?>

        <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
        <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
        <script src="https://cdn.datatables.net/1.10.25/js/dataTables.bootstrap4.min.js"></script>
        <script src="https://cdn.datatables.net/buttons/1.6.5/js/dataTables.buttons.min.js"></script>
        <script src="https://cdn.datatables.net/select/1.3.1/js/dataTables.select.min.js"></script>
        <script src="http://localhost/Try/plugins/toastr/toastr.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.2/dist/jquery.validate.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.2/dist/additional-methods.min.js"></script>
        <script src="assets/js/bootstrap.js"></script>
        <script>
            $(document).ready(function() 
            {
                toastr.options = {
                    "closeButton": false,
                    "debug": false,
                    "newestOnTop": false,
                    "progressBar": false,
                    "positionClass": "toast-top-right",
                    "preventDuplicates": false,
                    "onclick": null,
                    "showDuration": "300",
                    "hideDuration": "1000",
                    "timeOut": "5000",
                    "extendedTimeOut": "1000",
                    "showEasing": "swing",
                    "hideEasing": "linear",
                    "showMethod": "fadeIn",
                    "hideMethod": "fadeOut"
                }

                var table = $('#table_ex').DataTable({
                    autoWidth: false,
                    scrollX: true,
                    select: true,
                    'ajax': {
                        'url': 'upload_file.php',
                        'cache': false,
                        'data' : function(d){
                            d.function = "display"
                        },
                        'type': "POST",
                        'dataSrc': 'file'
                    },
                    'columns': [
                        { 'data': 'Id'},
                        { 'data': 'username'},
                        { 'data': 'title'}
                    ],
                    'rowId': 'Id',
                    pageLength : 5,
                    lengthMenu: [[5, 10, 20, -1], [5, 10, 20, 'Todos']],
                    dom: 'Bfrtip',
                    buttons: [
                        {
                            text: 'Add',
                            action: function ( e, dt, node, config ) {
                                $("#ModalAdd").modal("show")
                            }
                        },
                        {
                            text: 'Delete',
                            action: function ( e, dt, node, config ) {
                                if (table.row('.selected').id() === undefined) {
                                    // alert ();
                                    toastr.warning("Please select row that want to delete first");
                                } else {
                                    $.ajax({
                                        url: "upload_file.php",
                                        dataType: "text",
                                        type: "POST",
                                        data: {
                                            "function": "delete",
                                            "Id": table.row('.selected').id()
                                        },
                                        success: function (data_response) {

                                            // alert (data_response)

                                            if (data_response == 'Successfully') {
                                                toastr.success(" Message : " + data_response + " delete");
                                                table.ajax.reload();
                                            } else {
                                                toastr.error(data_response);
                                            }

                                        }
                                    })
                                }
                            }
                        }
                    ]
                });

                // Verify attachment
                $("#myfile").change(function () {

                    var fileExtension = ['txt'];
                    if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) 
                    {
                        $("#data_Student").val("");
                        toastr.error("Message: Only formats are allowed : "+fileExtension.join(', '))
                        return false;
                    }
                })

                var formadd = $("#formadd")

                $("#BtnAdd").click(function() {

                    var file_data = $('#myfile').prop('files');
                    var form_data = new FormData();
                    form_data.append('file', file_data);
                    form_data.append('function', 'Add');
                    form_data.append('myfile', $('#myfile').val());

                    if (formadd.valid()) {
                        $.ajax({
                            url: "upload_file.php",
                            dataType: "text",
                            type: "POST",
                            enctype: "multipart/form-data",
                            data: $("#formadd").serialize() + "&function=add",
                            success: function (data_response) {

                                if (data_response == 'Successfully') {
                                    toastr.success(" Message:" + data_response);
                                    table.ajax.reload();
                                    $("#ModalAdd").modal("hide")
                                } else {
                                    toastr.error(data_response);
                                }
                            }
                        })
                    }
                });

            });
        </script>
    </body>
</html>
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "try";
$bd = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password, $mysql_database) or die("Could not connect database");

if ($_POST['function'] == "display") 
{
    $sql = "SELECT * FROM fileup";
    $result = $bd->query($sql);
  
    if ($result->num_rows > 0) 
    {
        // output data of each row
        $no = 1;
        while($row = $result->fetch_assoc()) 
        {
            $Id       = $row['Id'];
            $username = $row['username'];
            $filename    = $row['title'];
        
            $post_data[] = array(
                "Id"=>$Id,
                "username"=>$username,
                "title"=>$filename,
                "no"=>$no);
            $no++;
        }
        echo $post_data = json_encode(array('file' => $post_data));
    } else {
        echo '{
        "sEcho": 1,
        "iTotalRecords": "0",
        "iTotalDisplayRecords": "0",
        "file": []
        }';
    }
    $bd->close();
}
else if ($_POST['function'] == "add") 
{
    $filename = $_FILES["myfile"]["name"]; 
    $fileTmpPath = $_FILES["myfile"]["tmp_name"];
    $fileNameCmps = explode(".", $filename);
    $fileExtensions = strtolower(end($fileNameCmps));
    $username = $_POST['username'];

        if (move_uploaded_file($fileTmpPath,"upload/".$filename))
        {
            $sql = "INSERT INTO fileup ";
            $sql .= "(username,title)";
            $sql .= "VALUES (";
            $sql .= "'$username',";
            $sql .= "'$filename')";

            $ret=mysqli_query($bd, $sql);
            if($ret)
            {
                echo "<br><br>";
                echo "Successfully";
                echo "<br><br>";
                echo "Uploaded!";
            }
            else
            {
                echo "<br><br>";
                echo "Error1";
            }
        } else {
            echo "Error2";
        }
    
}
else if ($_POST['function'] == "delete") 
{
    $Id = $_POST['Id'];
    $ret=mysqli_query($bd, "delete from fileup WHERE Id = $Id");
    if($ret)
    {
      echo "Successfully";
    }
    else
    {
      echo "Error";
    }
}
?>
  1. This is my php file, the error occurred in function Add on line $filename and $fileTmpPath
  2. The error

Notice: Undefined index: myfile

Notice: Trying to access array offset on value of type null

bella
  • 1
  • 1
  • Hi @bella, try printing the $_FILE and check the output. – baijugoradia Jan 18 '22 at 05:09
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Jan 18 '22 at 10:49

0 Answers0