duan39779 2018-01-01 14:20
浏览 78
已采纳

在Wordpress中,如何使用文件上载选项编写自定义表单并将记录保存在MySql中?

So far I have been able to make a custom form which upon successful entry save the value to a MySql table called "form_entry"

Below is the code for a form:

<form method="post" class="container">
<div class="row">
<div class="col-md-6 mb-3">
<label>Name</label>
<input type="text" name="myname" class="form-control" placeholder="Name" value="John Doe" required>
</div>
<div class="col-md-3 mb-3">
<label>State</label>
<input type="text" name="statename" class="form-control" placeholder="State" required>
</div>
</div>
<button class="btn btn-primary" type="submit" name="BtnSubmit" value="submit">Submit form</button>
</form>

And I insert a few codes in the functions.php under my template folder like this :

if(isset($_POST['BtnSubmit'])) {
    global $wpdb;
    $data_array = array(
                        'myname' => $_POST['myname'],
                        'statename'  => $_POST['statename'],

                        );

    $table_name = 'form_entry';
    $rowResult = $wpdb ->insert($table_name, $data_array, $format=NULL);

    if($rowResult == 1) {
        echo 'Success';
    }
else {
    echo ' Error in my pant';
}   
die;
}

This is working fine. But I want to add a file upload option in the form and save the uploaded file location to MySql. Please help.

  • 写回答

1条回答 默认 最新

  • douyan9398 2018-01-01 14:46
    关注

    You have to add one field into your html form. and add parameter for into form.

    <form method="post" class="container" enctype="multipart/form-data">
    
    <div class="row">
        <div class="col-md-6 mb-3">
            <label>File</label>
            <input type="file" name="myfile" class="form-control" required/>
        </div>
    </div>
    

    then after submit you have to save uploaded file at particular location and save that file into your db.

    if (isset($_POST['BtnSubmit'])) {
        $target = 'uploads/' . basename($_FILES['myfile']['name']);
    
        if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target)) {
            $fp = fopen($target, "r");
        }
        global $wpdb;
        $data_array = array(
                        'myname' => $_POST['myname'],
                        'statename'  => $_POST['statename'],
                        'filename' => $target
                     );
    }
    

    I think it will work for you !! feel free to ask me.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联
  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 利用pthon计算薄膜结构的光导纳